码迷,mamicode.com
首页 > 其他好文 > 详细

一天一个设计模式(13)——命令模式

时间:2017-07-19 10:42:15      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:public   imp   模式   color   设计   ons   on()   php   eol   

<?php
class Bulb {
    public function turnOn() {
        echo ‘Bulb has turned on‘;
    }

    public function turnOff() {
        echo ‘Bulb has turned off‘;
    }
}

interface Order {
    public function execute();
    public function undo();
    public function redo();
}

class TurnOn implements Order {
    private $_bulb;
    public function __construct(Bulb $bulb) {
        $this->_bulb = $bulb;
    }

    public function execute() {
        $this->_bulb->turnOn();
    }

    public function undo() {
        $this->_bulb->turnOff();
    }

    public function redo() {
        $this->_bulb->turnOn();
    }
}

class TurnOff implements Order {
    private $_bulb;

    public function __construct($bulb) {
        $this->_bulb = $bulb;
    }

    public function execute() {
        $this->_bulb->turnOff();
    }

    public function undo() {
        $this->_bulb->turnOn();
    }

    public function redo() {
        $this->_bulb->turnOff();
    }
}

class Control {
    public function submit($order) {
        $order->execute();
    }
}

$bulb = new Bulb();
$turnOn = new TurnOn($bulb);
$turnOff = new TurnOff($bulb);

$control = new Control();
$control->submit($turnOn);
echo PHP_EOL;
$control->submit($turnOff);

 

一天一个设计模式(13)——命令模式

标签:public   imp   模式   color   设计   ons   on()   php   eol   

原文地址:http://www.cnblogs.com/Bin-x/p/7203962.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!