设计模式之工厂方法模式(php)
2012-11-29 18:26
447 查看
<?php /** * 工厂方法 * */ //抽象产品类 abstract class PenCore{ public $color; abstract function writeWord($str); } //具体产品类 class RedPenCore extends PenCore { function __construct(){ $this->color = "<font color='red'>红色</font>"; } function writeWord($str){ echo "写出".$this->color."的字:$str"; } } class BluePenCore extends PenCore { function __construct(){ $this->color = "<font color='blue'>蓝色</font>"; } function writeWord($str){ echo "写出".$this->color."的字:$str"; } } class BlackPenCore extends PenCore { function __construct(){ $this->color = "黑色"; } function writeWord($str){ echo "写出".$this->color."的字:$str"; } } //抽象工厂类 abstract class BallPen{ function __construct(){ echo "生产了一支".$this->getPenCore()->color."笔芯的圆珠笔"; } abstract function getPenCore(); } //具体工厂类 class RedBallPen extends BallPen{ public function getPenCore(){ return new RedPenCore(); } } class BlueBallPen extends BallPen{ public function getPenCore(){ return new BluePenCore(); } } class BlackBallPen extends BallPen{ public function getPenCore(){ return new BlackPenCore(); } } echo "这个是工厂方法设计模式举例:<br/>"; $ballpen = new RedBallPen(); $penCore = $ballpen->getPenCore(); $penCore->writeWord("Hello world!"); echo "<br/>"; $ballpen = new BlueBallPen(); $penCore = $ballpen->getPenCore(); $penCore->writeWord("This is perfact!"); echo "<br/>"; $ballpen = new BlackBallPen(); $penCore = $ballpen->getPenCore(); $penCore->writeWord("It's OK!");
工厂方法:用户不必知道他所使用的对象如何创建的,只是需要知道用哪些方法可以使用即可。
相关文章推荐
- PHP和golang实现设计模式-工厂方法模式
- PHP生成对象之设计模式—工厂方法模式
- php设计模式 — 简单工厂模式(静态工厂方法模式)
- PHP设计模式(三),工厂方法模式
- php 设计模式(工厂方法模式)
- PHP设计模式(二)工厂方法模式(Factory Method For PHP)
- Php设计模式之工厂模式(二)【工厂方法模式 Factory Method】
- PHP设计模式系列(四):工厂方法模式
- PHP设计模式-工厂系列(二)-工厂方法模式
- php设计模式——工厂方法模式(Factory Method)
- Php设计模式之工厂模式(二)【工厂方法模式 Factory Method】
- php设计模式 — 工厂方法模式(多态性工厂模式) (虚拟构造子模式)
- 设计模式-使用php实现工厂方法模式
- php实现设计模式之 工厂方法模式
- 4. 星际争霸之php设计模式--工厂方法模式
- PHP中的设计模式-创建型-工厂方法模式
- PHP设计模式2-工厂方法模式
- php设计模式专题附源码(解释器模式、工厂方法模式、外观模式、装饰模式、建造者模式)
- PHP设计模式-工厂系列(二)-工厂方法模式
- PHP设计模式之工厂方法模式(Factory Method)