学习php设计模式 php实现策略模式(strategy)_php技巧
一、意图 定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换。策略模式可以使算法可独立于使用它的客户而变化 策略模式变化的是算法 二、策略模式结构图 三、策略模式中主要角色 <?php/** * 抽象策略角色,以接口实现 */interface Strategy { /** * 算法接口 */ public function algorithmInterface();} /** * 具体策略角色A */class ConcreteStrategyA implements Strategy { public function algorithmInterface() { echo 'algorithmInterface A<br />'; }} /** * 具体策略角色B */class ConcreteStrategyB implements Strategy { public function algorithmInterface() { echo 'algorithmInterface B<br />'; }} /** * 具体策略角色C */class ConcreteStrategyC implements Strategy { public function algorithmInterface() { echo 'algorithmInterface C<br />'; }} /** * 环境角色 */class Context { /* 引用的策略 */ private $_strategy; public function __construct(Strategy $strategy) { $this->_strategy = $strategy; } public function contextInterface() { $this->_strategy->algorithmInterface(); } } /** * 客户端 */class Client { /** * Main program. */ public static function main() { $strategyA = new ConcreteStrategyA(); $context = new Context($strategyA); $context->contextInterface(); $strategyB = new ConcreteStrategyB(); $context = new Context($strategyB); $context->contextInterface(); $strategyC = new ConcreteStrategyC(); $context = new Context($strategyC); $context->contextInterface(); } } Client::main();?> 以上就是使用php实现策略模式的代码,还有一些关于策略模式的概念区分,希望对大家的学习有所帮助。 |