标签:
作为一种创建型设计模式, 工厂方法(Factory Method)模式就是要创建"某种东西". 对于工厂方法模式, 要创建的"东西"是一个产品,这个产品与创建它的类之间不存在绑定.实际上,为了保持这种松耦合,客户会通过一个工厂发出请求. 再由工厂创建所请求的产品.也可以换种方式考虑, 利用工厂方法模式, 请求者只发出请求, 而不具体创建产品.
<?php abstract class Factory { //抽象的创建对象的方法 protected abstract function createProduct(); //该方法调用createProduct方法返回一个产品对象. public function start() { return $this->createProduct(); } }
<?php //产品接口 interface Product { public function getProperties(); }
<?php include_once(‘Factory.php‘); include_once(‘TextProduct.php‘); class TextFactory extends Factory { protected function createProduct() { $product = new TextProduct(); return $product->getProperties(); } }
<?php include_once(‘Factory.php‘); include_once(‘PhotoProduct.php‘); class PhotoFactory extends Factory { protected function createProduct() { $product = new PhotoProduct(); return $product->getProperties(); } }
<?php include_once(‘Product.php‘); class TextProduct implements Product { public function getProperties() { return "这里是文本产品"; } }
<?php include_once(‘Product.php‘); class PhotoProduct implements Product { //这是产品具有的方法 public function getProperties() { return "这里是图像产品"; } }
<?php include_once(‘PhotoFactory.php‘); include_once(‘TextFactory.php‘); class Client { public function __construct() { $this->somePhotoObject = new PhotoFactory(); echo $this->somePhotoObject->start() . ‘<br />‘; $this->someTextObject = new TextFactory(); echo $this->someTextObject->start() . ‘<br />‘; } } $worker = new Client();
这里是图像产品 这里是文本产品
<?php abstract class Factory { //抽象的创建对象的方法 protected abstract function createProduct(Product $product); //该方法由factoryMethod方法返回一个产品对象. public function start($product) { return $this->createProduct($product); } }
<?php include_once(‘Factory.php‘); include_once(‘Product.php‘); class CommonFactory extends Factory { protected function createProduct(Product $product) { return $product->getProperties(); } }
<?php //产品接口 interface Product { public function getProperties(); }
<?php include_once(‘Product.php‘); class PenProduct implements Product { public function getProperties() { return "钢笔产品"; } }
<?php include_once(‘CommonFactory.php‘); include_once(‘PenProduct.php‘); class Client { public function __construct() { $commonFactory = new CommonFactory(); echo $commonFactory->start(new PenProduct()); } } $worker = new Client();
钢笔产品
标签:
原文地址:http://www.cnblogs.com/chenqionghe/p/4771210.html