7.php策略模式

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

<?php
class 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);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值