How to organize conversion logic for strategy pattern?
https://softwareengineering.stackexchange.com/questions/264799
-
06-10-2020 - |
题
I have a Color
class. It has a property model
which is a class that implements ColorModel
interface, this property could be a RGB
, Hex
or HSL
classes which implementing ColorModel
interface.
// Color.php
class Color {
protected $model;
public static function factory (Model $model) {
return new Color($model);
}
public function __construct (Model $model) {
$this->model = $model;
}
public function getModel () {
return $this->model;
}
public function set ($color) {
$this->model->set($color);
}
public function raw ($string = false) {
return $this->model->raw($string);
}
public function check (Color $color) {
return get_class($this->model) === get_class($color->getModel());
}
public function isModel ($type) {
return $type === $this->model->getName();
}
// Converter probably suppose to be a strategy which converts color model to another color model
public function convert (Converter $convert) {
// I'm stack here...
}
}
// ColorModel.php
interface ColorModel {
// Parser is a class which parses input string/int and converts it to components
public function __construct (Parser $parser, $x, $y, $z);
public function raw ($string = false);
public function set ($color);
public function getName ();
}
I'm not sure how to implement the conversion of ColorModel
s. How can I implement conversion of those different models without having to create every class for each set (RGB2HSL
, HSL2RGB
. Let's say I add LAB
class four another classes: LAB2RGB
, LAB2HSL
, HSL2LAB
, RGB2LAB
, and more, and more)? It's possible at all?
Thank you for attention!
解决方案
If you have a ColorModel
that can represent all possible colors and that you can convert to without loss of information, then you can designate that ColorModel
as the 'canonical' model.
The conversion between arbitrary ColorModel
s then becomes a two-step process: First you convert from the source model to the canonical model and after that you convert from the canonical model to the target model.
This means that for each ColorModel
, you need one Converter
that can convert between that model and the canonical model (in both directions). For the canonical model this Converter
would implement the identity transformation, so that you don't need special logic if the source or target model happens to be the canonical model.