##一、创建型设计模式
####抽象工厂设计模式(abstract_factory)
抽象工厂模式(Abstact Factory)是一种常见的软件设计模式。该模式为一个产品族提供了统一的创建接口。当需要这个产品族的某一系列的时候,可以为此系列的产品族创建一个 具体的工厂类。
抽象工厂模式(Abstract Factory Pattern):提供一个创建一系列相关或相互依赖对象的接口,而无须指定它们具体的类。抽象工厂模式又称为Kit模式
";
}
public function watch()
{
echo "I'm watching TV
";
}
}
interface PC{
public function work();
public function play();
}
class LenovoPc implements PC
{
public function work()
{
echo "I'm working on a Lenovo computer
";
}
public function play()
{
echo "Lenovo computers can be used to play games
";
}
}
abstract class Factory{
abstract public static function createPc();
abstract public static function createTv();
}
class ProductFactory extends Factory
{
public static function createTV()
{
return new HaierTv();
}
public static function createPc()
{
return new LenovoPc();
}
}
$newTv = ProductFactory::createTV();
$newTv->open();
$newTv->watch();
$newPc = ProductFactory::createPc();
$newPc->work();
$newPc->play();
####简单工厂模式(simple_factory)
简单工厂模式(Simple Factory Pattern):又称为静态工厂方法(Static Factory Method)模式。
在简单工厂模式中,可以根据参数的不同返回不同类的实例。简单工厂模式专门定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类。
//简单工厂模式
class Cat
{
function __construct()
{
echo "I am Cat class
";
}
}
class Dog
{
function __construct()
{
echo "I am Dog class
";
}
}
class Factory
{
public static function CreateAnimal($name){
if ($name == 'cat') {
return new Cat();
} elseif ($name == 'dog') {
return new Dog();
}
}
}
$cat = Factory::CreateAnimal('cat');
$dog = Factory::CreateAnimal('dog');
####工厂方法模式(factory_method)
工厂方法模式(Factory Method Pattern)又称为工厂模式,也叫虚拟构造器(Virtual Constructor)模式或者多态工厂(Polymorphic Factory)模式
在工厂方法模式中,工厂父类负责定义创建产品对象的公共接口,而工厂子类则负责生成具体的产品对象,这样做的目的是将产品类的实例化操作延迟到工厂子类中完成,即通过工厂子类来确定究竟应该实例化哪一个具体产品类。
";
}
public function say(){
echo "I am Cat class
";
}
}
class Dog implements Animal
{
public function run(){
echo "I'm running fast
";
}
public function say(){
echo "I am Dog class
";
}
}
abstract class Factory{
abstract static function createAnimal();
}
class CatFactory extends Factory
{
public static function createAnimal()
{
return new Cat();
}
}
class DogFactory extends Factory
{
public static function createAnimal()
{
return new Dog();
}
}
$cat = CatFactory::createAnimal();
$cat->say();
$cat->run();
$dog = DogFactory::createAnimal();
$dog->say();
$dog->run();
####原型设计模式(prototype)
原型模式是一种创建型设计模式,Prototype模式允许一个对象再创建另外一个可定制的对象,根本无需知道任何如何创建的细节,工作原理是:通过将一个原型对象传给那个要发动创建的对象,这个要发动创建的对象通过请求原型对象拷贝它们自己来实施创建。
Prototype.php
/**抽象原型类
* Class Prototype
*/
abstract class Prototype
{
abstract function cloned();
}
/**具体原型类
* Class Plane
*/
class Plane extends Prototype
{
public $color;
function Fly()
{
echo "飞机飞啊飞!
";
}
function cloned()
{
return clone $this;
}
}
client.php
header("Content-Type:text/html;charset=utf-8");
//------------------------原型模式测试代码------------------
require_once "./Prototype/Prototype.php";
$plane1=new Plane();
$plane1->color="Blue";
$plane2=$plane1->cloned();
$plane1->Fly();
$plane2->Fly();
echo "plane1的颜色为:{$plane1->color}
";
echo "plane2的颜色为:{$plane2->color}
";
####单例设计模式(singleton)
单例模式(Singleton Pattern),也叫单子模式,又名单件模式或单态模式
实现单例模式的思路是:
一个类能返回对象一个引用(永远是同一个)和一个获得该实例的方法(必须是静态方法,通常使用getInstance这个名称);
当我们调用这个方法时,如果类持有的引用不为空就返回这个引用,如果类保持的引用为空就创建该类的实例并将实例的引用赋予该类保持的引用;
同时我们还将该类的构造函数定义为私有方法,这样其他处的代码就无法通过调用该类的构造函数来实例化该类的对象,只有通过该类提供的静态方法来得到该类的唯一实例。
class Singleton
{
private static $instance;
//私有构造方法,禁止使用new创建对象
private function __construct(){}
public static function getInstance(){
if (!isset(self::$instance)) {
self::$instance = new self;
}
return self::$instance;
}
//将克隆方法设为私有,禁止克隆对象
private function __clone(){}
public function say()
{
echo "这是用单例模式创建对象实例
";
}
public function operation()
{
echo "这里可以添加其他方法和操作
";
}
}
// $shiyanlou = new Singleton();
$shiyanlou = Singleton::getInstance();
$shiyanlou->say();
$shiyanlou->operation();
$newShiyanlou = Singleton::getInstance();
var_dump($shiyanlou === $newShiyanlou);
####构造者设计模式(builder)
构造者模式(Builder Pattern),又可以称为生成器模式
将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
构造者模式是一步一步创建一个复杂的对象,它允许用户只通过指定复杂对象的类型和内容就可以构建它们,用户不需要知道内部的具体构建细节
abstract class Builder
{
protected $car;
abstract public function buildPartA();
abstract public function buildPartB();
abstract public function buildPartC();
abstract public function getResult();
}
class CarBuilder extends Builder
{
function __construct()
{
$this->car = new Car();
}
public function buildPartA(){
$this->car->setPartA('发动机');
}
public function buildPartB(){
$this->car->setPartB('轮子');
}
public function buildPartC(){
$this->car->setPartC('其他零件');
}
public function getResult(){
return $this->car;
}
}
class Car
{
protected $partA;
protected $partB;
protected $partC;
public function setPartA($str){
$this->partA = $str;
}
public function setPartB($str){
$this->partB = $str;
}
public function setPartC($str){
$this->partC = $str;
}
public function show()
{
echo "这辆车由:".$this->partA.','.$this->partB.',和'.$this->partC.'组成';
}
}
class Director
{
public $myBuilder;
public function startBuild()
{
$this->myBuilder->buildPartA();
$this->myBuilder->buildPartB();
$this->myBuilder->buildPartC();
return $this->myBuilder->getResult();
}
public function setBuilder(Builder $builder)
{
$this->myBuilder = $builder;
}
}
$carBuilder = new CarBuilder();
$director = new Director();
$director->setBuilder($carBuilder);
$newCar = $director->startBuild();
$newCar->show();
##二、结构型设计模式
####适配器设计模式(adapter)
适配器模式(Adapter Pattern) ,有时候也称包装样式或者包装。
将一个接口转换成客户希望的另一个接口,适配器模式使接口不兼容的那些类可以一起工作,其别名为包装器(Wrapper)。适配器模式既可以作为类结构型模式,也可以作为对象结构型模式。
class Adaptee
{
public function realRequest()
{
echo "这是被适配者真正的调用方法";
}
}
interface Target{
public function request();
}
class Adapter implements Target
{
protected $adaptee;
function __construct(Adaptee $adaptee)
{
$this->adaptee = $adaptee;
}
public function request()
{
echo "适配器转换:";
$this->adaptee->realRequest();
}
}
$adaptee = new Adaptee();
$target = new Adapter($adaptee);
$target->request();
####装饰器设计模式(decorator)
其别名也可以称为包装器(Wrapper),与适配器模式的别名相同,但它们适用于不同的场合。根据翻译的不同,装饰模式也有人称之为“油漆工模式”
动态地给一个对象增加一些额外的职责(Responsibility),就增加对象功能来说,装饰模式比生成子类实现更为灵活
abstract class Component {
abstract public function operation();
}
class MyComponent extends Component
{
public function operation()
{
echo "这是正常的组件方法
";
}
}
abstract class Decorator extends Component {
protected $component;
function __construct(Component $component)
{
$this->component = $component;
}
public function operation()
{
$this->component->operation();
}
}
class MyDecorator extends Decorator
{
function __construct(Component $component)
{
parent::__construct($component);
}
public function addMethod()
{
echo "这是装饰器添加的方法
";
}
public function operation()
{
$this->addMethod();
parent::operation();
}
}
$component = new MyComponent();
$da = new MyDecorator($component);
$da->operation();
####代理模式(proxy)
给某一个对象提供一个代 理,并由代理对象控制对原对象的引用
";
}
}
class Proxy implements Subject
{
protected $realSubject;
function __construct()
{
$this->realSubject = new RealSubject();
}
public function beforeRequest()
{
echo "Proxy::beforeRequest
";
}
public function request()
{
$this->beforeRequest();
$this->realSubject->request();
$this->afterRequest();
}
public function afterRequest()
{
echo "Proxy::afterRequest
";
}
}
$proxy = new Proxy();
$proxy->request();
####桥接模式(bridge)
桥接模式(bridge),又称为柄体(Handle and Body)模式或接口(Interface)模式
将抽象部分与它的实现部分分离,使它们都可以独立地变化
';
}
}
/**
* drawAPI2
*/
class DrawingAPI2 implements DrawingAPI
{
public function drawCircle($x,$y,$radius)
{
echo "API2.circle at (".$x.','.$y.') radius '.$radius.'
';
}
}
/**
*shape接口
*/
interface Shape{
public function draw();
public function resize($radius);
}
class CircleShape implements Shape
{
private $x;
private $y;
private $radius;
private $drawingAPI;
function __construct($x,$y,$radius,DrawingAPI $drawingAPI)
{
$this->x = $x;
$this->y = $y;
$this->radius = $radius;
$this->drawingAPI = $drawingAPI;
}
public function draw()
{
$this->drawingAPI->drawCircle($this->x,$this->y,$this->radius);
}
public function resize($radius)
{
$this->radius = $radius;
}
}
$shape1 = new CircleShape(1,2,4,new DrawingAPI1());
$shape2 = new CircleShape(1,2,4,new DrawingAPI2());
$shape1->draw();
$shape2->draw();
$shape1->resize(10);
$shape1->draw();
####组合模式(composite)
组合模式(Composite Pattern),又叫部分整体模式,是用于把一组相似的对象当作一个单一的对象。
组合模式依据树形结构来组合对象,用来表示部分以及整体层次。
这种模式创建了一个包含自己对象组的类。该类提供了修改相同对象组的方式。
name = $name;
}
public function getName(){
return $this->name;
}
//增加节点
abstract function add(CompanyBase $c);
//删除节点
abstract function remove(CompanyBase $c);
//输出节点信息
abstract function show($deep);
//节点职责
abstract function work($deep);
}
/**
* 公司类
*/
class Company extends CompanyBase{
protected $item = [];
public function add(CompanyBase $c){
$nodeName = $c->getName();
if(!isset( $this->item[$nodeName] )){
$this->item[$nodeName] = $c;
}else{
throw new Exception("该节点已存在,节点名称:".$nodeName);
}
}
public function remove(CompanyBase $c){
$nodeName = $c->getName();
if(isset( $this->item[$nodeName] )){
unset($this->item[$nodeName]);
}else{
throw new Exception("该节点不存在,节点名称:".$nodeName);
}
}
public function show($deep = 0){
echo str_repeat("-",$deep).$this->name;
echo "
";
foreach($this->item as $value){
$value->show($deep+4);
}
}
public function work($deep = 0){
foreach($this->item as $value){
echo str_repeat(" ",$deep)."[{$this->name}]
";
$value->work($deep+2);
}
}
}
/**
* 人力资源部门
*/
class HumanResources extends CompanyBase{
public function add(CompanyBase $c){
throw new Exception("该节点下不能增加节点");
}
public function remove(CompanyBase $c){
throw new Exception("该节点下无子节点");
}
public function show($deep = 0){
echo str_repeat("-",$deep).$this->name;
echo "
";
}
public function work($deep = 0){
echo str_repeat(" ",$deep)."人力资源部门的工作是为公司招聘人才";
echo "
";
}
}
/**
* 商务部门
*/
class Commerce extends CompanyBase{
public function add(CompanyBase $c){
throw new Exception("该节点下不能增加节点");
}
public function remove(CompanyBase $c){
throw new Exception("该节点下无子节点");
}
public function show($deep = 0){
echo str_repeat("-",$deep).$this->name;
echo "
";
}
public function work($deep = 0){
echo str_repeat(" ",$deep)."商务部门的工作是为公司赚取利润";
echo "
";
}
}
/****************************************************************************************/
$c = new Company("北京某科技公司");
$h = new HumanResources("人力资源部门");
$com = new Commerce("商务部门");
$c->add($h);
$c->add($com);
//天津分公司
//为了偷懒,分公司的部门直接copy母公司的
$c1 = new Company("天津分公司");
$c1->add($h);
$c1->add($com);
$c->add($c1);
//武汉分公司
$c2 = new Company("武汉分公司");
$c2->add($h);
$c2->add($com);
$c->add($c2);
//使用公司功能
$c->show();
$c->work();
####外观模式(facade)
外观模式(facade),又称为门面模式
外部与一个子系统的通信必须通过一个统一的外观对象进行,为子系统中的一组接口提供一个一致的界面,外观模式定义了一个高层接口,这个接口使得这一子系统更加容易使用
";
}
}
class SystemB
{
public function operationB()
{
echo "operationB
";
}
}
class SystemC
{
public function operationC()
{
echo "operationC
";
}
}
class Facade
{
protected $systemA;
protected $systemB;
protected $systemC;
function __construct()
{
$this->systemA = new SystemA();
$this->systemB = new SystemB();
$this->systemC = new SystemC();
}
public function myOperation()
{
$this->systemA->operationA();
$this->systemB->operationB();
$this->systemC->operationC();
}
}
$facade = new Facade();
$facade->myOperation();
####享元模式(flyweight)
享元模式(flyweight),又称为轻量级模式
运用共享技术有效地支持大量细粒度对象的复用。系统只使用少量的对象,而这些对象都很相似,状态变化很小,可以实现对象的多次复用
intrinsicState = $str;
}
public function operation()
{
echo 'MyFlyweight['.$this->intrinsicState.'] do operation.
';
}
}
class FlyweightFactory
{
protected static $flyweightPool;
function __construct()
{
if (!isset(self::$flyweightPool)) {
self::$flyweightPool = [];
}
}
public function getFlyweight($str)
{
if (!array_key_exists($str,self::$flyweightPool)) {
$fw = new MyFlyweight($str);
self::$flyweightPool[$str] = $fw;
return $fw;
} else {
echo "aready in the pool,use the exist one:
";
return self::$flyweightPool[$str];
}
}
}
$factory = new FlyweightFactory();
$fw = $factory->getFlyweight('one');
$fw->operation();
$fw1 = $factory->getFlyweight('two');
$fw1->operation();
$fw2 = $factory->getFlyweight('one');
$fw2->operation();
##三、行为型设计模式
####中介者模式(mediator)
又称为调停者模式
用一个中介对象来封装一系列的对象交互,中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互
mediator = $mediator;
}
}
class ColleagueA extends Colleague
{
public function sendMsg($toWho,$msg)
{
echo "Send Msg From ColleagueA To: ".$toWho . '
';
$this->mediator->opreation($toWho,$msg);
}
public function receiveMsg($msg)
{
echo "ColleagueA Receive Msg: ".$msg . '
';
}
}
class ColleagueB extends Colleague
{
public function sendMsg($toWho,$msg)
{
echo "Send Msg From ColleagueB To: ".$toWho . '
';
$this->mediator->opreation($toWho,$msg);
}
public function receiveMsg($msg)
{
echo "ColleagueB Receive Msg: ".$msg . '
';
}
}
abstract class Mediator{
abstract public function opreation($id,$message);
abstract public function register($id,Colleague $colleague);
}
class MyMediator extends Mediator
{
protected static $colleagues;
function __construct()
{
if (!isset(self::$colleagues)) {
self::$colleagues = [];
}
}
public function opreation($id,$message)
{
if (!array_key_exists($id,self::$colleagues)) {
echo "colleague not found";
return;
}
$colleague = self::$colleagues[$id];
$colleague->receiveMsg($message);
}
public function register($id,Colleague $colleague)
{
if (!in_array($colleague, self::$colleagues)) {
self::$colleagues[$id] = $colleague;
}
$colleague->setMediator($this);
}
}
$colleagueA = new ColleagueA();
$colleagueB = new ColleagueB();
$mediator = new MyMediator();
$mediator->register(1,$colleagueA);
$mediator->register(2,$colleagueB);
$colleagueA->sendMsg(2,'hello admin');
$colleagueB->sendMsg(1,'shiyanlou');
####状态设计模式(state)
其别名为状态对象(Objects for States)
允许一个对象在其内部状态改变时改变它的行为,对象看起来似乎修改了它的类
state = StateA::getInstance();
}
public function changeState(State $state)
{
$this->state = $state;
}
public function request()
{
$this->state->handle($this);
}
}
abstract class State{
abstract function handle(Context $context);
}
class StateA extends State
{
private static $instance;
private function __construct(){}
private function __clone(){}
public static function getInstance()
{
if (!isset(self::$instance)) {
self::$instance = new self;
}
return self::$instance;
}
public function handle(Context $context)
{
echo "doing something in State A.\n done,change state to B
";
$context->changeState(StateB::getInstance());
}
}
class StateB extends State
{
private static $instance;
private function __construct(){}
private function __clone(){}
public static function getInstance()
{
if (!isset(self::$instance)) {
self::$instance = new self;
}
return self::$instance;
}
public function handle(Context $context)
{
echo "doing something in State B.\n done,change state to A
";
$context->changeState(StateA::getInstance());
}
}
$context = new Context();
$context->request();
$context->request();
$context->request();
$context->request();
####责任链模式(responsibility_chain)
责任链模式(Chain of Responsibility Pattern)为请求创建了一个接收者对象的链。
这种模式给予请求的类型,对请求的发送者和接收者进行解耦。这种类型的设计模式属于行为型模式
successor=$successor;
}
abstract public function HandleRequest($request);
}
//具体处理者角色(ConcreteHandler:President)
class ConcreteHandle1 extends Handler
{
public function HandleRequest($request)
{
if($request>=0&&$request<10){
var_dump(self::class.':'.$request);
}elseif ($this->successor!=null){
$this->successor->HandleRequest($request);
}
}
}
class ConcreteHandle2 extends Handler
{
public function HandleRequest($request)
{
if($request>=10&&$request<20){
var_dump(self::class.':'.$request);
}elseif ($this->successor!=null){
$this->successor->HandleRequest($request);
}
}
}
class ConcreteHandle3 extends Handler
{
public function HandleRequest($request)
{
if($request>=20&&$request<30){
var_dump(self::class.':'.$request);
}elseif ($this->successor!=null){
$this->successor->HandleRequest($request);
}
}
}
$h1=new ConcreteHandle1();
$h2=new ConcreteHandle2();
$h3=new ConcreteHandle3();
$h1->SetSuccessor($h2);
$h2->SetSuccessor($h3);
$h1->HandleRequest(5);
$h1->HandleRequest(15);
$h1->HandleRequest(25);
####观察者模式(observer)
观察者模式又叫做发布-订阅(Publish/Subscribe)模式、
模型-视图(Model/View)模式、源-监听器(Source/Listener)模式或从属者(Dependents)模式
定义对象间的一种一对多依赖关系,使得每当一个对象状态发生改变时,其相关依赖对象皆得到通知并被自动更新
$value) {
$value->update($this);
}
}
}
class MySubject extends Subject
{
protected $state;
public function setState($state)
{
$this->state = $state;
}
public function getState()
{
return $this->state;
}
}
class MyObeserver extends Obeserver
{
protected $obeserverName;
function __construct($name)
{
$this->obeserverName = $name;
}
public function update(Subject $sub)
{
$state = $sub->getState();
echo "Update Obeserver[".$this->obeserverName.'] State: '.$state . '
';
}
}
$subject = new MySubject();
$one = new MyObeserver('one');
$two = new MyObeserver('two');
$subject->attach($one);
$subject->attach($two);
$subject->setState(1);
$subject->notify();
echo "---------------------
";
$subject->setState(2);
$subject->deattach($two);
$subject->notify();
####策略模式(strategy)
策略模式让算法独立于使用它的客户而变化,也称为政策模式(Policy)
策略模式(Strategy Pattern):定义一系列算法,将每一个算法封装起来,并让它们可以相互替换。
";
}
}
class StrategyB extends Strategy
{
public function use()
{
echo "这是使用策略B的方法
";
}
}
class Context
{
protected $startegy;
public function setStrategy(Strategy $startegy)
{
$this->startegy = $startegy;
}
public function use()
{
$this->startegy->use();
}
}
$context = new Context();
$startegyA = new StrategyA();
$startegyB = new StrategyB();
$context->setStrategy($startegyA);
$context->use();
$context->setStrategy($startegyB);
$context->use();
####命令模式(command)
别名为动作(Action)模式或事务(Transaction)模式
将一个请求封装为一个对象,从而使我们可用不同的请求对客户进行参数化;对请求排队或者记录请求日志,以及支持可撤销的操作
Action";
}
}
abstract class Command{
protected $receiver;
function __construct(Receiver $receiver)
{
$this->receiver = $receiver;
}
abstract public function Execute();
}
class MyCommand extends Command
{
function __construct(Receiver $receiver)
{
parent::__construct($receiver);
}
public function Execute()
{
$this->receiver->Action();
}
}
class Invoker
{
protected $command;
function __construct(Command $command)
{
$this->command = $command;
}
public function Invoke()
{
$this->command->Execute();
}
}
$receiver = new Receiver();
$command = new MyCommand($receiver);
$invoker = new Invoker($command);
$invoker->Invoke();
解释器模式 用于分析一个实体的关键元素,并且针对每个元素提供自己的解释或相应动作。解释器模式非常常用,比如PHP的模板引擎 就是非常常见的一种解释器模。
代码一:解释器模式
_username = $username;
}
public function getProfilePage()
{
$profile = "I like never again
";
$profile .= "I love all of the songs, My favorite CD:
";
$profile .= "{{myCD.getTitle}}
";
$profile .= "My name is ";
$profile .= "{{myCD.getName}}";
return $profile;
}
}
/**
*ad
*/
class userCD
{
protected $_user = NULL;
public function setUser($user)
{
$this->_user = $user;
}
public function getTitle()
{
return 'test';
}
public function getName()
{
return '111';
}
}
/**
* interpreter
*/
class userCDInterpreter
{
protected $_user = NULL;
function setUser($user)
{
$this->_user = $user;
}
public function getInterpreted()
{
$profile = $this->_user->getProfilePage();
if (preg_match_all('/\{\{myCD\.(.*?)\}\}/', $profile, $triggers, PREG_SET_ORDER)) {
$replacements = array();
foreach ($triggers as $trigger) {
$replacements[] = $trigger[1];
}
$replacements = array_unique($replacements);
$myCD = new userCD();
$myCD->setUser($this->_user);
foreach ($replacements as $replacement) {
$profile = str_replace("{{myCD.{$replacement}}}", call_user_func(array($myCD, $replacement)), $profile);
}
}
return $profile;
}
}
$username = 'aaron';
$user = new User($username);
$interpreter = new userCDInterpreter();
$interpreter->setUser($user);
$echo = $interpreter->getInterpreted();
print "{$username}'s Profile
";
print $echo;
代码二:解释器模式
content;
}
}
//抽象解释器
abstract class AbstractInterpreter{
abstract function interpret($content);
}
//具体解释器,实现抽象解释器的抽象方法
class ChineseInterpreter extends AbstractInterpreter{
function interpret($content){
for($i=1;$i";break;
case "1": echo "一个人
";break;
case "2": echo "二个人
";break;
case "3": echo "三个人
";break;
case "4": echo "四个人
";break;
case "5": echo "五个人
";break;
case "6": echo "六个人
";break;
case "7": echo "七个人
";break;
case "8": echo "八个人
";break;
case "9": echo "九个人
";break;
default:echo "其他";
}
}
}
}
class EnglishInterpreter extends AbstractInterpreter{
function interpret($content){
for($i=1;$i";break;
case "1": echo "This is one people
";break;
case "2": echo "This is two people
";break;
case "3": echo "This is three people
";break;
case "4": echo "This is four people
";break;
case "5": echo "This is five people
";break;
case "6": echo "This is six people
";break;
case "7": echo "This is seven people
";break;
case "8": echo "This is eight people
";break;
case "9": echo "This is nine people
";break;
default:echo "others";
}
}
}
}
//封装好的对具体解释器的调用类,非解释器模式必须的角色
class Interpreter{
private $interpreter;
private $content;
function __construct($expression){
$this->content = $expression->getContent();
if($this->content[0] == "Chinese"){
$this->interpreter = new ChineseInterpreter();
}else{
$this->interpreter = new EnglishInterpreter();
}
}
function execute(){
$this->interpreter->interpret($this->content);
}
}
//测试
$expression = new Expression();
$expression->content = array("Chinese",3,2,4,4,5);
$interpreter = new Interpreter($expression);
$interpreter->execute();
$expression = new Expression();
$expression->content = array("English",1,2,3,0,0);
$interpreter = new Interpreter($expression);
$interpreter->execute();
//结果:
三个人
二个人
四个人
四个人
五个人
This is one people
This is two people
This is three people
This is nobody
This is nobody
?>
代码三:解释器模式
迭代器模式是遍历集合的成熟模式,迭代器模式的关键是将遍历集合的任务交给一个叫做迭代器的对象,它的工作时遍历并选择序列中的对象,而客户端程序员不必知道或关心该集合序列底层的结构。
代码一:迭代器模式
author = $author;
$this->title = $title;
}
public function getAuthor(): string
{
return $this->author;
}
public function getTitle(): string
{
return $this->title;
}
public function getAuthorAndTitle(): string
{
return $this->getTitle().' by '.$this->getAuthor();
}
}
books[] = $book;
}
public function removeBook(Book $bookToRemove)
{
foreach ($this->books as $key => $book) {
if ($book->getAuthorAndTitle() === $bookToRemove->getAuthorAndTitle()) {
unset($this->books[$key]);
}
}
$this->books = array_values($this->books);
}
public function count(): int
{
return count($this->books);
}
public function current(): Book
{
return $this->books[$this->currentIndex];
}
public function key(): int
{
return $this->currentIndex;
}
public function next()
{
$this->currentIndex++;
}
public function rewind()
{
$this->currentIndex = 0;
}
public function valid(): bool
{
return isset($this->books[$this->currentIndex]);
}
}
addBook(new Book('Learning PHP Design Patterns', 'William Sanders'));
$bookList->addBook(new Book('Professional Php Design Patterns', 'Aaron Saray'));
$bookList->addBook(new Book('Clean Code', 'Robert C. Martin'));
$books = [];
foreach ($bookList as $book) {
$books[] = $book->getAuthorAndTitle();
}
$this->assertEquals(
[
'Learning PHP Design Patterns by William Sanders',
'Professional Php Design Patterns by Aaron Saray',
'Clean Code by Robert C. Martin',
],
$books
);
}
public function testCanIterateOverBookListAfterRemovingBook()
{
$book = new Book('Clean Code', 'Robert C. Martin');
$book2 = new Book('Professional Php Design Patterns', 'Aaron Saray');
$bookList = new BookList();
$bookList->addBook($book);
$bookList->addBook($book2);
$bookList->removeBook($book);
$books = [];
foreach ($bookList as $book) {
$books[] = $book->getAuthorAndTitle();
}
$this->assertEquals(
['Professional Php Design Patterns by Aaron Saray'],
$books
);
}
public function testCanAddBookToList()
{
$book = new Book('Clean Code', 'Robert C. Martin');
$bookList = new BookList();
$bookList->addBook($book);
$this->assertCount(1, $bookList);
}
public function testCanRemoveBookFromList()
{
$book = new Book('Clean Code', 'Robert C. Martin');
$bookList = new BookList();
$bookList->addBook($book);
$bookList->removeBook($book);
$this->assertCount(0, $bookList);
}
}
在不破坏封闭的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。又叫做快照模式(Snapshot Pattern)或Token模式
liveLevel,$this->attackLevel,$this->defenseLevel));
}
//恢复状态
public function RecoveryState(RoleStateMemento $_memento)
{
$this->liveLevel = $_memento->liveLevel;
$this->attackLevel = $_memento->attackLevel;
$this->defenseLevel = $_memento->defenseLevel;
}
//------------其他属性及操作--------------
//获得初始状态
public function GetInitState()
{
$this->defenseLevel = 100;
$this->attackLevel = 100;
$this->liveLevel = 100;
}
//状态显示
public function StateDisplay()
{
echo "角色状态:
";
echo "生命力:{$this->liveLevel}
";
echo "攻击力:{$this->attackLevel}
";
echo "防御力:{$this->defenseLevel}
";
}
//被攻击
public function BeenAttack()
{
$this->liveLevel -= 9.5;
if($this->liveLevel<=0)
{
$this->liveLevel = 0;
echo "呃,该角色阵亡了!
";
echo "Game Over!
";
return;
}
$this->attackLevel -= 1.1;
if($this->attackLevel<=0)
{
$this->attackLevel = 0;
}
$this->defenseLevel -= 0.5;
if($this->defenseLevel<=0)
{
$this->defenseLevel = 0;
}
}
}
//角色状态存储箱类
class RoleStateMemento
{
public $liveLevel;
public $attackLevel;
public $defenseLevel;
public function RoleStateMemento($_ll,$_al,$_dl)
{
$this->liveLevel=$_ll;
$this->attackLevel=$_al;
$this->defenseLevel=$_dl;
}
}
//游戏角色状态管理者类
class RoleStateManager
{
public $memento;
}
//开战前
$ufo = new GameRole();
$ufo->GetInitState();
echo "----------------开战前-----------------
";
$ufo->StateDisplay();
//保存进度
$roleMan = new RoleStateManager();
$roleMan->memento = $ufo->SaveState();
echo "----------------战斗中-----------------
";
$num=1;
//大战Boss5个回合
for ($i = 0; $i <13;$i++ )
{
echo "-------------第{$num}回合-------------
";
$ufo->BeenAttack();
$ufo->StateDisplay();
$num++;
//角色阵亡
if($ufo->liveLevel<=0)
{
break;
}
}
echo "----------------恢复状态-----------------
";
//恢复之前状态
$ufo->RecoveryState($roleMan->memento);
$ufo->StateDisplay();
代码二:备忘录模式
time --;
}
public function addMoney(){
$this->money += 1000;
}
public function changeTitle($title){
$this->title = $title;
}
/**
* 备份当前的基础数据属性
* @dateTime 2017-02-13
*/
public function backup(){
return new Backup($this->time,$this->money,$this->title);
}
/**
* 数据还原
* @dateTime 2017-02-13
*/
public function reback(Backup $backup){
$this->time = $backup->time;
$this->title = $backup->title;
$this->money = $backup->money;
}
}
/**
* 存储类
*/
class Backup{
public $time;
public $title;
public $money;
public function __construct($time,$money,$title){
$this->time = $time;
$this->title = $title;
$this->money = $money;
}
}
/**
* 管理者类
*/
class Manager{
public $data;
}
//客户端应用
$Sponsor = new Sponsor();
//备份初始状态
$Manager = new Manager();
$Manager->data = $Sponsor -> backup();
while($Sponsor->time > 0){
$Sponsor -> addMoney();
$Sponsor -> subTime();
if($Sponsor->money >= 1000000)
$Sponsor -> changeTitle("骄傲者");
if($Sponsor->money >= 10000000)
$Sponsor -> changeTitle("能力者");
if($Sponsor->money >= 100000000)
$Sponsor -> changeTitle("成功者");
}
var_dump($Sponsor);
//还原初始状态
$Sponsor->reback($Manager->data);
var_dump($Sponsor);
在模板模式(Template Pattern)中,一个抽象类公开定义了执行它的方法的方式/模板。它的子类可以按需要重写方法实现,但调用将以抽象类中定义的方式进行
代码一:模板模式
//Game.class.php (抽象父类,模板类)
initialize();
//开始游戏
$this->startPlay();
//结束游戏
$this->endPlay();
}
}
//Cricket.class.php (具体子类)
';
}
public function startPlay()
{
echo "Cricket Game Started. Enjoy the game!";
echo '
';
}
public function endPlay()
{
echo "Cricket Game Finished!";
echo '
';
}
}
//Football.class.php (具体子类)
';
}
public function startPlay()
{
echo "Football Game Started. Enjoy the game!";
echo '
';
}
public function endPlay()
{
echo "Football Game Finished!";
echo '
';
}
}
//template.php
play();
$game2 = new Football();
$game2->play();
代码二:模板模式
// IHook.php
fullCost = $fullCost;
$this->hook = $hook;
$this->addGoods();
$this->addShippingHook();
$this->displayCost();
}
protected abstract function addGoods();
protected abstract function addShippingHook();
protected abstract function displayCost();
}
//Concrete.php
fullCost = $this->fullCost * 0.8;
}
protected function addShippingHook()
{
if(!$this->hook)
{
$this->fullCost += 12.95;
}
}
protected function displayCost()
{
echo "您需要支付: " . $this->fullCost . '元
';
}
}
//Client.php
totalCost = $goodsTotal;
$this->hook = $this->totalCost >= 200;
$concrete = new Concrete();
$concrete->templateMethod($this->totalCost, $this->hook);
}
}
$worker = new Client(100);
$worker = new Client(200);
表示一个作用于某对象结构中的各元素的操作。它使你可以在不改变各元素类的前提下定义作用于这些元素的新操作。
代码一:访问者模式
//Computer.class.php (电脑类)
_items[] = $unit;
}
public function accept(Visitor $visitor)
{
foreach ($this->_items as $item) {
$item->accept($visitor);
}
}
}
//Unit.class.php (组件抽象父类)
$method($this);
echo '
';
}
}
}
//Cpu.class.php (具体组件:cpu)
//Memory.class.php(具体组件:内存)
//Keyboard.class.php(具体组件:键盘)
//Visitor.class.php (访问者类)
getName() . "\n";
}
public function visitMemory(Memory $memory)
{
echo "hello, " . $memory->getName() . "\n";
}
public function visitKeyboard(Keyboard $keyboard)
{
echo "hello, " . $keyboard->getName() . "\n";
}
}
//visitor.php (客户端类)
add(new Cpu());
$computer->add(new Memory());
$computer->add(new Keyboard());
$computer->accept(new Visitor());
参考资料:
实验楼
图说设计模式
设计模式
百度百科等