问题
I know that there are many similar questions, but I don't understand most of those questions because I'm not sure if I know what a factory method pattern is..
so..after reading many examples over the web, I came up with the following simple classes.
Am I doing it correctly?
abstract class Driveable
{
abstract public function start();
abstract public function stop();
}
class CoupeDriveable extends Driveable
{
public function start()
{
}
public function stop()
{
}
}
class MotorcycleDriveable extends Driveable
{
public function start()
{
}
public function stop()
{
}
}
class SedanDriveable extends Driveable
{
public function start()
{
}
public function stop()
{
}
}
class DriveableFactory
{
static public function create($numberOfPeople){
if( $numberOfPeople == 1 )
{
return new MotorcycleDriveable;
}
elseif( $numberOfPeople == 2 )
{
return new CoupleDriveable;
}
elseif( $numberOfPeople >= 3 && $numberOfPeople < 4)
{
return SedanDriveable;
}
}
}
class App
{
static public function getDriveableMachine($numberOfPeople)
{
return DriveableFactory::create($numberOfPeople);
}
}
$DriveableMachine = App::getDriveableMachine(2);
$DriveableMachine->start();
回答1:
Yes. That's a correct implementation of the factory method
pattern.
Edit +1 for silent's comment. Should indeed be on coderewiew, didn't thought about that.
回答2:
To be exact: This is a Factory pattern, not a Factory method pattern.
The difference is that in the Factory pattern you have a separate factory object (DriveableFactory
), whereas in the Factory method pattern, the create()
method would be a member of the Driveable
base class. I'm not familiar with php, and the pattern doesn't seem to be applicable to your concrete scenario anyway, so I cannot give you a code example here.
But in any case, you have to distinguish the two patterns. I know that there is a lot of confusion around them, and the Wikipedia entry for Factory method pattern is just plain wrong - among a lot of other sources that can be found on the web. But it's better to be exact on this, because it's essential for communication to mean the same things when you're using the same words...
HTH - Thomas
来源:https://stackoverflow.com/questions/7976974/is-this-correct-factory-method-pattern