7.php策略模式

来源:互联网 发布:苍穹软件使用教程 编辑:程序博客网 时间:2024/06/10 13:58

    策略模式就是自己并不对相应的事务做处理而是转交给更具体的对象去做,策略模式有很多变种,这里我们介绍两种。

<?phpclass OWN{    private $name = '';    private $obj = NULL;        public function __construct($name){        $this->name = $name;    }        //代处理对象的传入    function addObject($obj){        $this->obj = $obj;    }        function get(){        echo $this->obj->doing();    }}//处理接口interface Doing{    function doing();}//XML处理class XMLdoing implements Doing{    function doing(){        return "XML方式处理了!";    }}//JSON处理class JSONdoing implements Doing{    function doing(){        return "JSON方式处理了!";    }}$own = new OWN('名字');$obj = new XMLdoing();$own->addObject($obj);$own->get();
    当然这里仅仅对单个对象方式做了处理,我们一开始也可以定义一个数组队列,根据数组的键来调用不同的处理对象。但我们使用拼装类名的方式来组织对象,而没有必要一次性创建所有的对象。

<?php//创建数学运算用父类abstract class Math{    protected $num1;    protected $num2;        function __construct($num1, $num2){        $this->num1 = $num1;        $this->num2 = $num2;    }        abstract function count();}//进行加法运算class MathAdd extends Math{    function count(){        return (int)$this->num1 + (int)$this->num2;    }}//进行减法运算class MathSubtract extends Math{    function count(){        return (int)$this->num1 - (int)$this->num2;    }}//创建调用接口final class Client{    static function handle($way, $num1, $num2){        //用处理方法组装类名        $calculate = "Math".$way;        $obj = new $calculate($num1, $num2);        return $obj->count();    }}echo Client::handle("Add", 5, 10);


0 0
原创粉丝点击