I have the following factory class, which takes as a parameter a value $type
based on which it creates a different class, and some additional optional parameters, which are passed only to the class that needs them.
class OptionalParametersDto extends DataTransferObject
{
public ?bool $someValue = null;
public ?string $someString = null;
}
Both ClassA
and ClassB
expect in the constructor an instance of OptionalParametersDto
.
class A{
public function __construct(OptionalParametersDto $parameters){}
}
class B{
public function __construct(OptionalParametersDto $parameters){}
}
class Factory
{
public function create(string $type, array $optionalParameters)
{
if($type === 'A'){
return new ClassA(new OptionalParametersDto(['someValue' => $optionalParameters['someValue']]));
}
if($type === 'B'){
return new ClassB(new OptionalParametersDto());
}
}
}
it seems that the factory pattern is being abused when it needs to know which parameters need to be passed to each class.
Also passing a dto that might have fields that one class needs, but the other class does not need, looks like a code smell.
Is there a more elegant way to do this ?
Aucun commentaire:
Enregistrer un commentaire