Reputation: 19242
I have 3 classes:
Class_A
and Class_B
I then have a class which basically chooses which class (A or B) to instantiate based on some condition
class Chooser
{
public static function choose($condition)
{
$class = 'Class_' . ucfirst($condition);
return new $class();
}
}
I then call the static choose method and it returns an instance of the right class (A or B)
Chooser::choose($condition);
My questions:
Chooser::choose($condition);
. If I do this, would it now mess with the pattern?Upvotes: 1
Views: 72
Reputation: 197775
I would not call it a pattern as it's concrete code. Patterns are just descriptions of what can be done how. It looks a bit like an implementation of the Factory pattern and if you call it Factory, most users might get a quicker understanding of what it is for.
However it's probably better described as parametrized object creation, as you don't verify that the class it generates implements a specific interface, which is part of a common Factory pattern.
That ensures that the function returns a type with a specific interface.
class Chooser
{
/**
* @return interface
*/
public static function choose($condition)
{
$class = 'Class_' . ucfirst($condition);
if (!is_a($class, 'interface'))
return NULL;
return new $class();
}
}
This needs some specific PHP versions and can be influenced by bugs in PHP because of is_a
. There are alternative ways to check whether a specific classname implements an interface though. I leave this as an exercise.
You need also decide whether the chooser()
function returns NULL
if condition does not lead to an object or if it should throw an exception.
Upvotes: 2
Reputation: 14935
Yes, your example fits in as Factory Pattern. It's one of the creational pattern.
In your original code, do all the coding based upon your interface. The chooser would be responsible for making the correct choice of class to instantiate. You would achieve high separation of concerns by doing it. Read more about it here. http://www.oodesign.com/factory-pattern.html
Upvotes: 3