当前位置: 移动技术网 > IT编程>开发语言>PHP > 【php设计模式】策略模式

【php设计模式】策略模式

2019年06月21日  | 移动技术网IT编程  | 我要评论

  策略模式是针对一组算法,将每一种算法都封装到具有共同接口的独立的类中,从而是它们可以相互替换。策略模式的最大特点是使得算法可以在不影响客户端的情况下发生变化,从而改变不同的功能。

<?php
interface stratege{
    public function dooperation($int1,$int2);
}

class operationadd implements stratege{
    public function dooperation($int1,$int2){
        return $int1 + $int2;
    }
}

class operationsub implements stratege{
    public function dooperation($int1,$int2){
        return $int1 - $int2;
    }
}

class context{
    public $stratege;
    public function __construct(stratege $stra){
        $this->stratege = $stra;
    }
    public function executestrategy($int1,$int2){
        echo $this->stratege->dooperation($int1,$int2)."\n";
    }
}


$add = new operationadd();
$context_add = new context($add);
$context_add->executestrategy(5,3); //输出8

$sub = new operationsub();
$context_sub = new context($sub);
$context_sub->executestrategy(5,3); //输出2

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网