工厂模式:工厂方法——用PHP改写head first中的例子
工厂方法(Factory Method)模式是指:定义一个创建对象的接口,但由子类决定要实例化的类是哪一个。工厂方法让类把实例化推迟到了子类。在这个例子中,生产何种pizza是在继承了抽象类的子类中进行的。Pizza类
<?php
abstract class Pizza {
public $name;
public $dough;
public $sauce;
function prepare() {
echo 'Preparing '.$this->name.'<br />';
echo 'Tossing dough...<br />';
echo 'Adding sause...<br />';
}
function bake() {
echo 'Bake for 25 minutes at 350';
}
function cut() {
echo 'Cutting the pizza into diagonal slices';
}
function box() {
echo 'Place pizza in official PizzaStore box';
}
function getName() {
echo$this->name;
}
}
?>
PizzaStore类
<?php
abstract class PizzaStore {
abstract function createPizza($type);
public function orderPizza($type) {
$pizza = $this->createPizza($type);
$pizza->prepare();
$pizza->bake();
$pizza->cut();
$pizza->box();
return $pizza;
}
}
?>
NYPizzaStore类
<?php
class NYPizzaStore extends PizzaStore {
function createPizza($type) {
if($type == 'cheese') {
return new NYStyleCheesePizza();
} elseif ($type == 'pepperioni') {
return new NYStylePepperioniPizza();
} elseif ($type == 'clam') {
return new NYSytleClamPizza();
} elseif ($type == 'veggie') {
return new NYSytleVeggiePizza();
}
}
}
?>
NYStyleCheesePizza 类
<?php
class NYStyleCheesePizza extends Pizza {
public function __construct() {
$this->name = '"NY Style Sauce and Cheese Pizza';
$this->dough = "Thin Crust Dough";
$this->sauce = "Marinara Sauce";
}
}
?>
客户
<?php
include_once 'Pizza.php';
include_once 'PizzaStore.php';
include_once 'NYPizzaStore.php';
include_once 'NYStyleCheesePizza.php';
$pizzaStore = new NYPizzaStore();
$pizza = $pizzaStore->orderPizza('cheese');
$pizza->getName();
?>
页:
[1]