《大话设计模式》装饰模式-穿什么场景-PHP版代码

Standard

装饰模式
穿什么场景

<?php
/**
 * 装饰模式 穿什么场景
 * @author 叶茂盛 anson.ye#gmail.com  http://yemaosheng.com
 */
interface Component{
        public function Show();
}
 
class Person implements Component{
        protected $_name;
 
        public function __construct($name){
                $this->_name = $name;
        }
        public function Show(){
                echo "装扮的".$this->_name;
        }
}
 
 
abstract class Finery implements Component{
        protected $_component;
        public function Decorate(Component $component){
                $this->_component = $component;
        }
        public function Show(){
                $this->_component->Show();
        }
}
class Sneakers extends Finery{
        public function Show(){
                echo "旅游鞋 ";
                parent::Show();
        }
}
class TShirts extends Finery{
        public function Show(){
                echo "T恤 ";
                parent::Show();
        }
}
class BigTrouser extends Finery{
        public function Show(){
                echo "垮裤 ";
                parent::Show();
        }
}
class Tie extends Finery{
        public function Show(){
                echo "领带 ";
                parent::Show();
        }
}
class Suit extends Finery{
        public function Show(){
                echo "西装 ";
                parent::Show();
        }
}
class LeatherShoes extends Finery{
        public function Show(){
                echo "皮鞋 ";
                parent::Show();
        }
}
class Main{
        public static function run(){
                $xc = new Person("小菜");
 
                $sk = new Sneakers();
                $ts = new TShirts();
                $bt = new BigTrouser();
 
                echo "装扮1:\n";
                $sk->Decorate($xc);
                $ts->Decorate($sk);
                $bt->Decorate($ts);
                $bt->Show();
 
                $dn = new Person("大鸟");
 
                $ti = new Tie();
                $si = new Suit();
                $ls = new LeatherShoes();
 
                echo "\n装扮2:\n";
                $ti->Decorate($dn);
                $si->Decorate($ti);
                $ls->Decorate($si);
                $ls->Show();
 
        }
}
Main::run();
?>
//php Decorator.php 
//装扮1:
//垮裤 T恤 旅游鞋 装扮的小菜
//装扮2:
//皮鞋 西装 领带 装扮的大鸟

转载请注明出处 http://yemaosheng.com

《大话设计模式》策略模式-商场促销场景-PHP版代码

Standard

策略模式
商场促销场景

<?php
/**
 * 策略模式 商场促销场景
 * @author 叶茂盛 anson.ye#gmail.com  http://yemaosheng.com
 */
abstract class CashSuper{
        public abstract function acceptCash($money);
}
class CashNormal extends CashSuper{
        public function acceptCash($money){
                return $money;
        }
}
class CashRebate extends CashSuper{
        private $_moneyRebate;
        public function __construct($moneyRebate){
                $this->_moneyRebate = $moneyRebate;
        }
        public function acceptCash($money){
                return $money * $this->_moneyRebate;
        }
}
class CashReturn extends CashSuper{
        private $_moneyCondition;
        private $_moneyReturn;
        public function __construct($moneyCondition, $moneyReturn){
                $this->_moneyCondition = $moneyCondition;
                $this->_moneyReturn = $moneyReturn;
        }
        public function acceptCash($money){
                if( $money >= $this->_moneyCondition )
                        $result = $money - floor($money / $this->_moneyCondition) * $this->_moneyReturn;
 
                return $result;
        }
}
 
class CashContext{
        private $_cs;
 
        public function __construct(CashSuper $csuper){
                $this->_cs = $csuper;
        }
        public function GetResult($money){
                return $this->_cs->acceptCash($money);
        }
}
 
//简单工厂
class CashContextFactory{
        private $_cs;
 
        public function __construct($type){
                switch ($type) {
                case "a":
                    $this->_cs = new CashNormal();
                    break;
                case "b":
                    $this->_cs = new CashReturn("300", "100");
                    break;
                case "c":
                    $this->_cs = new CashRebate("0.8");
                    break;
                }
        }
        public function GetResult($money){
                return $this->_cs->acceptCash($money);
        }
}
 
class Main{
        public static function run_Strategy(){
                fwrite(STDOUT, "数量: ");
                $number = trim(fgets(STDIN));
 
                fwrite(STDOUT, "单价: ");
                $price = trim(fgets(STDIN));
 
                fwrite(STDOUT, "折扣: a = 原价 b = 返利 c = 8折 \nEnter your discount: ");
                $discount = trim(fgets(STDIN));
 
                switch ($discount) {
                case "a":
                    $cc = new CashContext( new CashNormal() );
                    break;
                case "b":
                    $cc = new CashContext( new CashReturn("300", "100") );
                    break;
                case "c":
                    $cc = new CashContext( new CashRebate("0.8") );
                    break;
                }
 
                echo "\n======帐单======\n数量:" .$number. "\n单价". $price. "\n折后总价:". $cc->GetResult($number*$price);
        }
        public static function run_StrategyFactory(){
                fwrite(STDOUT, "数量: ");
                $number = trim(fgets(STDIN));
 
                fwrite(STDOUT, "单价: ");
                $price = trim(fgets(STDIN));
 
                fwrite(STDOUT, "折扣: a = 原价 b = 返利 c = 8折 \nEnter your discount: ");
                $discount = trim(fgets(STDIN));
 
                $cc = new CashContextFactory($discount);
 
                echo "\n======帐单======\n数量:" .$number. "\n单价". $price. "\n折后总价:". $cc->GetResult($number*$price);
        }
}
Main::run_StrategyFactory();
?>
//php Strategy.php 
//数量: 10
//单价: 120
//折扣: a = 原价 b = 返利 c = 8折 
//Enter your discount: c
 
//======帐单======
//数量:10
//单价120
//折后总价:960

转载请注明出处 http://yemaosheng.com

《大话设计模式》访问者模式-男人和女人场景-PHP版代码

Standard

访问者模式
男人和女人场景

<?php
/**
 * 访问者模式 男人和女人场景
 * @author 叶茂盛 anson.ye#gmail.com  http://yemaosheng.com
 */
abstract class Action{
        public abstract function GetManConclusion(Man $concreteElementA);
        public abstract function GetWomanConclusion(Woman $concreteElementB);
}
abstract class Person{
        public abstract function Accept(Action $visitor);
}
 
class Success extends Action{
        public function GetManConclusion(Man $concreteElementA){
                echo "男人".__CLASS__."时 背后多半有一个伟大的女人\n";
        }
        public function GetWomanConclusion(Woman $concreteElementB){
                echo "女人".__CLASS__."时 背后多半有一个不太成功的男人\n";
        }
}
class Failing extends Action{
        public function GetManConclusion(Man $concreteElementA){
                echo "男人".__CLASS__."时 闷头喝酒,谁也不用劝\n";
        }
        public function GetWomanConclusion(Woman $concreteElementB){
                echo "女人".__CLASS__."时 眼泪汪汪,谁也劝不了\n";
        }
}
class Amativeness extends Action{
        public function GetManConclusion(Man $concreteElementA){
                echo "男人".__CLASS__."时 凡事不懂也要装懂\n";
        }
        public function GetWomanConclusion(Woman $concreteElementB){
                echo "女人".__CLASS__."时 遇事懂也装作不懂\n";
        }
}
 
class Man extends Person{
        public function Accept(Action $visitor){
                $visitor->GetManConclusion($this);
        }
}
class Woman extends Person{
        public function Accept(Action $visitor){
                $visitor->GetWomanConclusion($this);
        }
}
 
class ObjectStructure{
        private $_elements;
 
        public function __construct(){
                $this->_elements = array();
        }
        public function Attach(Person $element){
                $this->_elements[ count($this->_elements) ] = $element;
        }
        public function Display(Action $visitor){
                foreach($this->_elements as $element){
                        $element->Accept($visitor);
                }
        }
}
 
class Main{
        public static function run(){
                $o = new ObjectStructure;
                $o->Attach(new Man());
                $o->Attach(new Woman());
 
                $v1 = new Success;
                $o->Display($v1);
 
                $v2 = new Failing;
                $o->Display($v2);
 
                $v3 = new Amativeness;
                $o->Display($v3);
        }
}
Main::run();
?>
//php Visitor.php 
//男人Success时 背后多半有一个伟大的女人
//女人Success时 背后多半有一个不太成功的男人
//男人Failing时 闷头喝酒,谁也不用劝
//女人Failing时 眼泪汪汪,谁也劝不了
//男人Amativeness时 凡事不懂也要装懂
//女人Amativeness时 遇事懂也装作不懂

转载请注明出处 http://yemaosheng.com

《大话设计模式》解释器模式-音符场景-PHP版代码

Standard

解释器模式
音符场景

<?php
/**
 * 解释器模式 音符场景
 * @author 叶茂盛 anson.ye#gmail.com  http://yemaosheng.com
 */
class PlayContext{
	private $PlayText;
 
        public function __get($property_name){
                if(isset($this->$property_name)){
                        return($this->$property_name);
                }else{
                        return(NULL);
                }
        }
        public function __set($property_name, $value){
                $this->$property_name = $value;
        }
 
}
 
abstract class Expression{
	public function Interpret(PlayContext $context){
		if( strlen($context->PlayText)==0 ){
			return;
		}else{
			$PlayKey = substr($context->PlayText, 0, 1);
			$context->PlayText = substr($context->PlayText, 2);
			$PlayValue = substr( $context->PlayText, 0, strpos($context->PlayText, ' ') );
			$context->PlayText = substr($context->PlayText, strpos($context->PlayText, ' ') + 1 );
 
			$this->Excute($PlayKey, $PlayValue);
		}
	}
	public abstract function Excute($key, $value);
}
 
//音符类
class Note extends Expression{
	public function Excute($key, $value){
		$note = "";
		switch($key){
		case "C":
			$note = "1";
			break;
		case "D":
			$note = "2";
			break;
		case "E":
			$note = "3";
			break;
		case "F":
			$note = "4";
			break;
		case "G":
			$note = "5";
			break;
		case "A":
			$note = "6";
			break;
		case "B":
			$note = "7";
			break;
		}
		echo $note . " ";
	}
}
//音阶类
class Scale extends Expression{
	public function Excute($key, $value){
		$scale = "";
		switch($value){
		case "1":
			$scale = "低音";
			break;
		case "2":
			$scale = "中音";
			break;
		case "3":
			$scale = "高音";
			break;
		}
		echo $scale . " ";
	}
}
//速度类
class Speed extends Expression{
	public function Excute($key, $value){
		$speed = "";
		if ( $value < 500 ) 
			$speed = "快速";
		elseif( $value >= 1000 )
			$speed = "慢速";
		else
			$speed = "中速";
 
		echo $speed . " ";
	}
}
 
class Main{
	public static function run(){
		$context = new PlayContext();
		$context->PlayText = "T 500 O 2 E 0.5 G 0.5 A 3 E 0.5 G 0.5 D 3 E 0.5 G 0.5 A 0.5 O 3 C 1 O 2 A 0.5 G 1 C 0.5 E 0.5 D 3";
		try{
			while ( strlen($context->PlayText) > 0 ){
				$str = substr($context->PlayText, 0, 1);
				switch($str){
				case "O":
					$expression = new Scale();
					break;
				case "T":
					$expression = new Speed();
					break;
				default:
					$expression = new Note();
					break;
				}
				$expression->Interpret($context);
			}
 
		} catch (Exception $e) {
			echo $e;
		}
	}
}
Main::run();
?>
//php Expression.php 
//中速 中音 3 5 6 3 5 2 3 5 6 高音 1 中音 6 5 1 3 2

转载请注明出处 http://yemaosheng.com

《大话设计模式》享元模式-网站场景-PHP版代码

Standard

享元模式
网站场景

<?php
/**
 * 享元模式 网站场景
 * @author 叶茂盛 anson.ye#gmail.com  http://yemaosheng.com
 */
class User{
	public $name;
	public function __construct($name){
		$this->name = $name;
	}
}
 
abstract class WebSite{
	abstract function __construct(User $user);
}
 
class ConcreteWebSite extends Website{
 
	private $_name;
 
	public function __construct($name){
		$this->_name = $name;
	}
	public function User(User $user){
		echo "网站分类:" . $this->_name . " 用户:" . $user->name . "\n";
	}
}
 
class WebSiteFactory{
 
	private $_websites;
	private $_ConcreteWetSite;
 
	public function __construct(){
		$this->_ConcreteWetSite = array();
	}
 
	public function GetWebSiteCategory($key){
		if( isset($websites[$key]) ){
			return $this->_websites[$key];
		}else{
			return $this->_websites[$key] = new ConcreteWebSite($key);
		}
	}
	public function GetWebSiteCount(){
		return count( $this->_websites );
	}
}
 
class Main{
	public static function run(){
		$WebSiteFactory = new WebSiteFactory;
		$f = new WebSiteFactory();
		$fx = $f->GetWebSiteCategory("产品展示");
		$fx->User(new User("小菜"));
 
		$fy = $f->GetWebSiteCategory("产品展示");
		$fy->User(new User("大鸟"));
 
		$fy = $f->GetWebSiteCategory("产品展示");
		$fy->User(new User("娇娇"));
 
		$fl = $f->GetWebSiteCategory("博客");
		$fl->User(new User("老顽童"));
 
		$fm = $f->GetWebSiteCategory("博客");
		$fm->User(new User("六仙"));
 
		$fn = $f->GetWebSiteCategory("博客");
		$fn->User(new User("南海"));
 
		echo "得到网站分类总数为:" .$f->GetWebSiteCount(). "\n";
	}
}
Main::run();
?>
//php Flyweight.php 
//网站分类:产品展示 用户:小菜
//网站分类:产品展示 用户:大鸟
//网站分类:产品展示 用户:娇娇
//网站分类:博客 用户:老顽童
//网站分类:博客 用户:六仙
//网站分类:博客 用户:南海
//得到网站分类总数为:2

转载请注明出处 http://yemaosheng.com

《大话设计模式》中介者模式-联合国场景-PHP版代码

Standard

中介者模式
联合国场景

<?php
/**
 * 中介者模式 联合国场景
 * @author 叶茂盛 anson.ye#gmail.com  http://yemaosheng.com
 */
abstract class UnitedNations{
        abstract function Declares($message, Country $colleague);
}
 
abstract class Country{
        private $mediator;
 
        public function __construct(UnitedNations $mediator){
                $this->mediator = $mediator;
        }
        public function mediator(){
                return $this->mediator;
        }
}
 
class USA extends Country{
        public function __construct(UnitedNations $mediator){
                parent::__construct($mediator);
        }
        public function Declares($message){
                parent::mediator()->Declares($message, $this);
        }
        public function GetMessage($message){
                echo "美国获得对方信息:" . $message ."\n";
        }
}
class Iraq extends Country{
        public function __construct(UnitedNations $mediator){
                parent::__construct($mediator);
        }
        public function Declares($message){
                parent::mediator()->Declares($message, $this);
        }
        public function GetMessage($message){
                echo "伊拉克获得对方信息:" . $message ."\n";
        }
}
class UnitedNationsSecurityCouncil extends UnitedNations{
        private $colleague1;
        private $colleague2;
 
        public function __get($property_name){
                if(isset($this->$property_name)){
                        return($this->$property_name);
                }
                else{
                        return(NULL);
                }
        }
        public function __set($property_name, $value){
                $this->$property_name = $value;
        }
 
        public function Declares($message, Country $colleague){
                if($colleague == $this->colleague1){
                        $this->colleague2->GetMessage($message);
                }else{
                        $this->colleague1->GetMessage($message);
                }
        }
}
class Main{
        public static function run(){
                $UNSC = new UnitedNationsSecurityCouncil();
 
                $c1 = new USA($UNSC);
                $c2 = new Iraq($UNSC);
 
                $UNSC->colleague1 = $c1;
                $UNSC->colleague2 = $c2;
 
                $c1->Declares("不准研制核武器,否则就打你!");
                $c2->Declares("我们没有研制核武器,但也不怕你打!");
        }
}
Main::run();
?>
//php Mediator.php  
//伊拉克获得对方信息:不准研制核武器,否则就打你!
//美国获得对方信息:我们没有研制核武器,但也不怕你打!

转载请注明出处 http://yemaosheng.com

《大话设计模式》职责链模式-小菜请假加薪场景-PHP版代码

Standard

职责链模式
小菜请假加薪场景

<?php
/**
 * 职责链模式 小菜请假加薪场景
 * @author 叶茂盛 anson.ye#gmail.com  http://yemaosheng.com
 */
abstract class Manager{
        public $name;
        public $superior;
 
        public function __construct($name){
                $this->name = $name;
        }
        public function SetSuperior(Manager $superior){
                $this->superior = $superior;
        }
}
 
class Request{
        private $requestType;
        private $requestContent;
        private $number;
 
        public function __get($property_name){
                if(isset($this->$property_name)){
                        return($this->$property_name);
                }else{
                        return(NULL);
                }
        }
 
        public function __set($property_name, $value){
                $this->$property_name = $value;
        }
}
 
class CommonManager extends Manager{
        public function __construct($name){
                parent::__construct($name);
        }
        public function RequestApplications(Request $request){
                if( $request->RequestType == "请假" && $request->Number <=2 ){
                        echo $this->name .":". $request->RequestContent ."数量". $request->Number ."被批准\n";
                }else{
                        if( $this->superior != null ){
                                $this->superior->RequestApplications($request);
                        }
                }
        }
}
class MajorManager extends Manager{
        public function __construct($name){
                parent::__construct($name);
        }
        public function RequestApplications(Request $request){
                if( $request->RequestType == "请假" && $request->Number <=5 ){
                        echo $this->name .":". $request->RequestContent ."数量". $request->Number ."被批准\n";
                }else{
                        if( $this->superior != null ){
                                $this->superior->RequestApplications($request);
                        }
                }
        }
}
class GeneralManager extends Manager{
        public function __construct($name){
                parent::__construct($name);
        }
        public function RequestApplications(Request $request){
                if( $request->RequestType == "请假" ){
                        echo $this->name .":". $request->RequestContent ."数量". $request->Number ."被批准\n";
                }elseif( $request->RequestType == "加薪" && $request->Number <=500 ){
                        echo $this->name .":". $request->RequestContent ."数量". $request->Number ."被批准\n";
                }elseif( $request->RequestType == "加薪" && $request->Number > 500 ){
                        echo $this->name .":". $request->RequestContent ."数量". $request->Number ."被否决\n";
                }
        }
}
 
class Main {
    public static function run() {
                $jinli = new CommonManager("经理老张");
                $zhongjian = new MajorManager("总监老赵");
                $zhongjinli = new GeneralManager("总经理老刘");
 
                $jinli->SetSuperior($zhongjian);
                $zhongjian->SetSuperior($zhongjinli);
 
                $request1 = new Request();
                $request1->RequestType = "请假";
                $request1->RequestContent = "小菜请假";
                $request1->Number = 1;
                $jinli->RequestApplications($request1);
 
                $request2 = new Request();
                $request2->RequestType = "请假";
                $request2->RequestContent = "小菜请假";
                $request2->Number = 5;
                $jinli->RequestApplications($request2);
 
                $request3 = new Request();
                $request3->RequestType = "加薪";
                $request3->RequestContent = "小菜要求加薪";
                $request3->Number = 500;
                $jinli->RequestApplications($request3);
 
                $request4 = new Request();
                $request4->RequestType = "加薪";
                $request4->RequestContent = "小菜要求加薪";
                $request4->Number = 1000;
                $jinli->RequestApplications($request4);
    }
}
Main::run();
?>
//php ChainOfResponsibility.php 
//经理老张:小菜请假数量1被批准
//总监老赵:小菜请假数量5被批准
//总经理老刘:小菜要求加薪数量500被批准
//总经理老刘:小菜要求加薪数量1000被否决

转载请注明出处 http://yemaosheng.com

《大话设计模式》命令模式-烤肉店点菜场景-PHP版代码

Standard

最近闲时在看早前公司里买的《大话设计模式》。
那本书上的代码是C#写的,下面是我用PHP改写的一些书中范例,初学者可以用其帮助强化下记忆。

命令模式
烧烤店点菜场景

<?php
/**
 * 命令模式 烤肉店点菜场景
 * @author 叶茂盛 anson.ye#gmail.com  http://yemaosheng.com
 */
interface Command {
    public function execute();
}
interface ListCommand extends Command {
    public function remove(Command $command);
    public function add(Command $command);
}
 /**
 * 命令集
 */
class MacroCommand implements ListCommand {
 
    private $_commandList;
 
    public function __construct() {
        $this->_commandList = array();
    }
 
    public function remove(Command $command) {
        $key = array_search($command, $this->_commandList);
        if ($key === FALSE) {
            return FALSE;
        }
        echo "去掉" . $command->name . "\n";
        unset($this->_commandList[$key]);
        return TRUE;
    }
 
    public function add(Command $command) {
        echo "点份" . $command->name . "\n";
        return array_push($this->_commandList, $command);
    }
 
    public function execute() {
        echo "确定下单\n";
        foreach ($this->_commandList as $command) {
            $command->execute();
        }
    }
}
 /**
 * 命令
 */
class BakeMutton implements Command {
 
    private $_barbecuer;
    public $name;
 
    public function __construct(Barbecuer $barbecuer) {
        $this->_barbecuer = $barbecuer;
        $this->name = __CLASS__;
    }
    public function execute() {
        $this->_barbecuer->bakeMutton();
    }
}
class BakeChicken implements Command {
 
    private $_barbecuer;
    public $name;
 
    public function __construct(Barbecuer $barbecuer) {
        $this->_barbecuer = $barbecuer;
        $this->name = __CLASS__;
    }
    public function execute() {
        $this->_barbecuer->bakeChicken();
    }
}
class BakeChickenWing implements Command {
 
    private $_barbecuer;
    public $name;
 
    public function __construct(Barbecuer $barbecuer) {
        $this->_barbecuer = $barbecuer;
        $this->name = __CLASS__;
    }
    public function execute() {
        $this->_barbecuer->bakeChickenWing();
    }
}
 /**
 * 烧烤厨师
 */
class Barbecuer {
 
    private $_name;
 
    public function __construct($name) {
        $this->_name = $name;
    }
 
    public function bakeMutton() {
        echo $this->_name . "开始烤羊肉.\n";
    }
    public function bakeChicken() {
        echo $this->_name . "开始烤鸡肉.\n";
    }
    public function bakeChickenWing() {
        echo $this->_name . "开始烤鸡翅膀.\n";
    }
}
 /**
 * 服务员
 */
class Waiter {
 
    private $_command;
 
    public function __construct(Command $command) {
        $this->_command = $command;
    }
 
    public function action() {
        $this->_command->execute();
    }
}
 /**
 * Main
 */
class Main {
    public static function run() {
        $barbecuer = new Barbecuer('烧烤厨师');
 
        $bakeMutton = new BakeMutton($barbecuer);
        $bakeChicken = new BakeChicken($barbecuer);
        $bakeChickenWing = new BakeChickenWing($barbecuer);
 
        $macroCommand = new MacroCommand();
        $macroCommand->add($bakeMutton);
        $macroCommand->add($bakeChicken);
        $macroCommand->add($bakeChickenWing);
 
        $waiter = new Waiter($macroCommand);
 
        $macroCommand->remove($bakeMutton);
 
        $waiter = new Waiter($macroCommand);
        $waiter->action();
    }
}
 
Main::run();
?>
//php command.php 
//点份BakeMutton
//点份BakeChicken
//点份BakeChickenWing
//去掉BakeMutton
//确定下单
//烧烤厨师开始烤鸡肉.
//烧烤厨师开始烤鸡翅膀.

转载请注明出处 http://yemaosheng.com

《一天一个设计模式》整理转载

Standard

<<一天一个设计模式>>
转自phpchina论坛 作者ID:kakashilw

一、工厂模式
1、先看一个简单的例子

<?php
interface IUser
{
  function getName();
}
class User implements IUser
{
  public static function Load( $id ) 
  {
        return new User( $id );
  }
  public static function Create( ) 
  {
        return new User( null );
  }
  public function __construct( $id ) { }
  public function getName()
  {
    return "Jack";
  }
}
$uo = User::Load( 1 );
echo( $uo->getName()."n" );
?>

2、一个稍微复杂但却相当经典的例子

<?php
//BT种子的接口
interface BT
{
    public function process();
}
//BT种子的下载处理类
class BTdown implements BT
{
    public function process()
    {
        //输出BT种子
        echo '输出BT种子';
    }
}
//BT种子的上传处理类
class BtUpload implements BT
{
    public function process()
    {
        //保存上传的BT种子
        echo '保存上传的BT种子';
    }
}
---------------------------------------------------------------
//生产BT种子处理对象的设备的接口
interface BTcreator
{
    public function createBTObject();
}
//生产BT种子下载处理对象的设备
class BTdownCreator implements BTcreator
{
    public function createBTObject()
    {
        /**
        * 如果不是管理员,送10点积分
        */
        //然后返回BT种子下载处理对象
        return new BTdown();
    }
}
//生产BT种子上传处理对象的设备
class BTUploadCreator implements BTcreator
{
    public function createBTObject()
    {
    /**
    * 如果不是管理员,扣10点积分
    */
    //然后返回BT种子下载处理对象
    return new BtUpload();
    }
}
------------------------------------------------------------------
//生产BT种子处理对象的工厂
class BtFactory
{
    //获取电影处理类的对象,参数为类名
    public function getBtObject($name)
    {
        switch ($name) {
        case 'BTdown':
        $creator = new BTdownCreator();
        break;
        case 'BtUpload':
        $creator = new BtUploadCreator();
        break;
    }
    return $creator->createBTObject();
}
}
---------------------------------------------------------------------
//获取bt工厂
$btFactory = new BtFactory();
//BT种子的下载处理
$what = 'BTdown';
$btObject = $btFactory->getBtObject($what);
$btObject->process();
//BT种子的上传处理
$what = 'BtUpload';
$btObject = $btFactory->getBtObject($what);
$btObject->process();
?>

二、单件模式

<?php
class userInfo
{
    private $userName;
    //唯一的实例
    private static $instance;
    //构造方法
    private function __construct()
    {
        //查询数据库,获得用户名
        $this->userName = 'lightsaber';
    }
    //获取对象实例
    public static function getInstance()
    {
        if (self::$instance=='') self::$instance = new userInfo();
        return self::$instance;
    }
    //返回用户信息
    public function getUserInfo()
    {
        return $this->userName;
    }
}
//获取唯一的实例
$userInfo = userInfo::getInstance();
//显示用户名
echo '用户名是'.$userInfo->getUserInfo().'<br>';
//天气播报
echo '向用户'.$userInfo->getUserInfo().'播报天气<br>';
?>

其实单件模式还是比较好理解的一个模式,比如上面这个例子,用在数据库链接上,就可以保证数据库的唯一连接了。
而单件模式也可以用于减少数据库的查询,感觉这个作用也是大大地~~~~,如下:

<?php
class userInfo
{
    private static $userName;
    //查询数据库,获得用户名
    private static function findUserInfo()
    {
        //查询数据库,获得用户名
        self::$userName = 'lightsaber';
    }
    public static function getUserInfo()
    {
        //判断是否已经获取了用户数据
        if (self::$userName=='') self::findUserInfo();
        return self::$userName;
    }
}
//显示用户名
echo '用户名是'.userInfo::getUserInfo().'<br>';
//天气播报
echo '向用户'.userInfo::getUserInfo().'播报天气<br>';
?>

三、备忘模式
今天学的是备忘模式,简单理解比喻下就是类似平时我们用的word”撤销”,”恢复”…
1.UNDO

<?php
//备忘类
class Memento
{
    public function backup()
    {
        //保存现有的分页样式
        echo '样式已经保存<br>';
    }
    public function restore()
    {
        //用保存的样式去覆盖
        echo '样式已经恢复<br>';
    }
}
----------------------------------------------------
//设置分页样式
class ListStyle
{
    //备忘对象
    private $memento;
 
    //构造方法
    public function __construct()
    {
        $this->memento = new Memento();
    }
    //设置样式
    public function setStyle()
    {
        //开始先备份样式
        $this->memento->backup();
        //设置样式
        echo '设置了样式<br>';
    }
    //撤销方法
     public function undo()
    {
        $this->memento->restore();
    }
}
----------------------------------------------------
$listStyle = new ListStyle();
//设置样式,同时备份
$listStyle->setStyle();
//撤销设置
$listStyle->undo();
?>

2.REDO

<?php
//备忘类
class Memento
{
    public function backup()
    {
        //保存现有的分页样式
        echo '样式已经保存<br>';
    }
 
    public function restore()
    {
        //用保存的样式去覆盖
        echo '样式已经恢复<br>';
    }
}
//设置分页样式
class ListStyle
{
    //备忘对象
    private $memento;
 
    //构造方法
    public function __construct()
    {
        $this->memento = new Memento();
    }
    //设置样式
    public function setStyle()
    {
        //开始先备份样式
        $this->memento->backup();
 
        //设置样式
        echo '设置了样式<br>';
    }
    //撤销方法
     public function undo()
    {
        //先保存,为了redo
        $this->memento->backup();
        $this->memento->restore();
    }
    //重做方法
    public function redo()
    {
        $this->memento->restore();
    }
}
$listStyle = new ListStyle();
//设置样式,同时备份
$listStyle->setStyle();
//撤销设置
$listStyle->undo();
//重做设置
$listStyle->redo();
?>

简单总结下,就是有相应的一个类,来做backup和restore用的…

四、策略模式
策略模式(Strategy),将不同情况的算法分拆到不同的类(比如advanceDiscountor类),然后调用者(discountor类)根据具体的情况,用算法类的对象来处理。

<? php
//打折接口
interface IDiscountor
{
    public function getDiscount();
}
------------------------------------------------------------------------------------
//普通用户打折类
class commonDiscountor implements IDiscountor 
{
    public function getDiscount()
    {
        $discount = 1;
        return $discount;
    }
}
//高级用户打折类
class advanceDiscountor implements IDiscountor 
{
    public function getDiscount()
    {
        $discount = 0.9;
        return $discount;
    }
}
//vip用户打折类
class vipDiscountor implements IDiscountor 
{
    public function getDiscount()
    {
        $discount = 0.8;
        return $discount;
    }
}
----------------------------------------------------------------------------------
//打折类
class discountor
{
    public function getDiscount($rank)
    {
        switch ($rank) {
        case 'common':
            $discountor = new commonDiscountor();
            break;
        case 'advance':
            $discountor = new advanceDiscountor();
            break;
        case 'vip':
            $discountor = new vipDiscountor();
            break;
        }
        return $discountor->getDiscount();
    }
} 
$discountor = new discountor();
echo $discountor->getDiscount('advance');
?>

五、状态模式

<?php
//积分基础类
class Point
{
    //积分
    public $point;
 
    public function showPoint()
    {
        //列出用户的积分
    }
    public function showUseRecord()
    {
        //列出用户的积分使用记录
    }
}
--------------------------------------------------------------------------
//积分低于500的类
class Point500 extends Point
{
    //显示提示
    public function showTips()
    {
            echo "客户发帖等行为可以增加积分";
    }
    //显示按钮
    public function showButton()
    {
            echo "";
    }
}
//积分大于500,低于1000的类
class Point600 extends Point
{
    //显示提示
    public function showTips()
    {
            echo "可以行使标准用户的权利";
    }
    //显示按钮
    public function showButton()
    {
            echo "标准用户功能的按钮";
    }
}
//积分大于1000的类
class Point1000 extends Point
{
    //显示提示
    public function showTips()
    {
            echo "可以行使高级用户的权利";
    }
    //显示按钮
    public function showButton()
    {
            echo "高级用户的按钮";
    }
}
--------------------------------------------------------------------------
//应用环境类,简单的理解为调用环境就可以了
class Context
{
    //积分对象
    public $pointObj;
 
    //设置一个积分对象
    public function setPointObj($point)
    {
        //低于500
        if ($point<500) {
            $this->pointObj = new Point500();
        }
        //大于1000
        elseif ($point>1000) {
            $this->pointObj = new Point1000();
        }
        //大于500,低于1000
        else {
            $this->pointObj = new Point600();
        }
    }
    public function showPoint()
    {
        $this->pointObj->showPoint();
    }
    public function showUseRecord()
    {
        $this->pointObj->showUseRecord();
    }
    //显示提示
    public function showTips()
    {
       $this->pointObj->showTips();
    }
    //显示按钮
    public function showButton()
    {
        $this->pointObj->showButton();
    }
}
--------------------------------------------------------------------------
$context = new Context();
$context->setPointObj(780);
//显示提示
$context->showTips();
?>

优点:更好的阅读,扩展,已经封装