定义
工厂方法模式
定义了一个创建对象的接口,但由子类
决定要实例化的类是哪一个。工厂方法让类把实例化推迟到了子类
。
工厂方法模式
通过让子类(NYPizzaStore, ChicagoPizzaStore)决定该创建的对象(NYStyleCheesePizza,ChicagoCheesePizza),来达到将对象创建的过程封装的目的。
类图
工厂模式定义
实例图
Creator Class
Product Class
实例
创建者
//创建者超类
abstruct class PizzaStore
{
public function orderPizza($type)
{
$pizza = $this->createPizza($type);
$pizza->prepare();
$pizza->bake();
$pizza->cut();
$pizza->box();
return $pizza;
}
abstract public function createPizza($type);
}
//参数化工厂方法
//具体创建者
class NYPizzaStore extends PizzaStore
{
public function createPizza($type)
{
if($type == 'cheese') {
$pizza = new NYStyleCheesePizza();
}elseif($type == 'peppernoi') {
$pizza = new NYStylePeppernoiPizza();
}elseif($type == 'clam') {
$pizza = new NYStyleClamPizza();
}
return $pizza;
}
}
//具体创建者
class ChicagoPizzaStore extends PizzaStore
{
public function createPizza($type)
{
if($type == 'cheese') {
$pizza = new ChicagoStyleCheesePizza();
}elseif($type == 'peppernoi') {
$pizza = new ChicagoStylePeppernoiPizza();
}elseif($type == 'clam') {
$pizza = new ChicagoStyleClamPizza();
}
return $pizza;
}
}
产品类
//产品超类
abstract class Pizza
{
private $name;
private $dough;
private $sauce;
private toppings = [];
private function prepare()
{
echo "Preparing ".$this->name;
echo "Tossing";
...
}
private function bake()
{
echo "bake";
}
private function cut()
{
echo "cut";
}
private function box()
{
echo "box";
}
public function getName()
{
return $this->name;
}
}
//具体产品
class NYStyleCheesePizza extends Pizza
{
public function __construct()
{
$this->name = "NY Style Souce and Cheese Pizza";
$this->dough = "NY dough";
$this->sauce = "NY sauce";
$this->toppings[] = "Cheese";
}
//也可以重写父类的方法 实现子类特有的制作工艺
}
测试
$nyStore = new NYPizzaStore();
$pizza = $nyStore->orderPizza("cheese");
echo $pizza->getName();