您实际上在示例中使用了一个简单的工厂,对我来说它看起来不错。有了这些要求,就没有必要去工厂方法模式了。
但是,我将尝试在这种情况下解释工厂方法。根据定义:
工厂方法模式定义了一个用于创建对象的接口,但让子类决定实例化哪个类。工厂方法让一个类将实例化推迟到
子类。
所以基本上你会有一个抽象工厂类,它定义了具体工厂中可以使用哪些创建方法,而后者将决定要创建哪些具体对象。
我能在你的场景中想到一个例子。假设您拥有不同品牌的 Drivables(例如宝马和本田)。所以你会有像BMWCoupeDrivable,
BMWMotorcycleDrivable, BMWSedanDrivable, HondaCoupeDrivable, HondaMotorcycleDrivable, HondaSedanDrivable 这样的课程。您将来可能还会添加更多品牌。在这种情况下,您可能是
最好使用工厂方法。
abstract class DriveableFactory
{
abstract public function create($numberOfPeople);
//-- Other methods here which manipulate the drivable
//-- e.g. testDrive()
}
class BMWDriveableFactory extends DriveableFactory
{
public function create($numberOfPeople){
if( $numberOfPeople == 1 )
{
return new BMWMotorcycleDriveable;
}
elseif( $numberOfPeople == 2 )
{
return new BMWCoupleDriveable;
}
elseif( $numberOfPeople >= 3 && $numberOfPeople < 4)
{
return BMWSedanDriveable;
}
}
}
class HondaDriveableFactory extends DriveableFactory
{
public function create($numberOfPeople){
if( $numberOfPeople == 1 )
{
return new HondaMotorcycleDriveable;
}
elseif( $numberOfPeople == 2 )
{
return new HondaCoupleDriveable;
}
elseif( $numberOfPeople >= 3 && $numberOfPeople < 4)
{
return HondaSedanDriveable;
}
}
}
为了更好的解释,我建议阅读 Head First Design Pattern。