设计模式按照作用可以分为3大类:创建型、结构型、行为型。
创建型设计模式工厂方法
- 参与者:客户、工厂、产品
- 场景:实例化对象的子类可能发生变化。
- 优点:方便修改,方便新增。
- 注意:client不会实例化所请求的产品,由具体的工厂实例化所请求的产品。
步骤:
1.创建工厂(工厂接口[抽象类])
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <?php
abstract class Creator { protected abstract function factoryMethod(); public function startFactory() { $mfg = $this->factoryMethod(); return $mfg; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| <?php
include_once('Creator.php'); include_once('TextProduct.php'); class TextFactory extends Creator { protected function factoryMethod() { $product = new TextProduct(); return($product->getProperties()); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| <?php
include_once('Creator.php'); include_once('GraphicProduct.php'); class GraphicFactory extends Creator { protected function factoryMethod() { $product = new GraphicProduct(); return($product->getProperties()); } }
|
2.产品接口
1 2 3 4 5 6
| <?php
interface Product { public function getProperties(); }
|
1 2 3 4 5 6 7 8 9 10 11 12
| <?php
include_once('Product.php'); class TextProduct implements Product { private $mfgProduct; public function getProperties() { $this->mfgProduct = 'This is text'; return $this->mfgProduct; } }
|
1 2 3 4 5 6 7 8 9 10 11 12
| <?php
include_once('Product.php'); class GraphicProduct implements Product { private $mfgProduct; public function getProperties() { $this->mfgProduct = 'This is graphic'; return $this->mfgProduct; } }
|
3.客户(客户并没有向产品直接做出请求,而是通过工厂来请求。)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| <?php
include_once('GraphicFactory.php'); include_once('TextFactory.php'); class Client { private $someGraphicObject; private $someTextObject; public function __construct() { $this->someGraphicObject = new GraphicFactory(); echo $this->someGraphicObject->startFactory() . "\n"; $this->someTextObject = new TextFactory(); echo $this->someTextObject->startFactory() . "\n"; } }
$worker = new Client();
|
未完待续 |