策略模式是一种行为设计模式, 它能让你定义一系列算法, 并将每种算法分别放入独立的类中,将行为转换为对象,以使算法的对象能够相互替换。
<?php //定义算法及抽象实现 interface strategy { function algorithmInterface(); } class concreteStrategyA implements strategy { function algorithmInterface() { echo '算法A'; } } class concreteStrategyB implements strategy { function algorithmInterface() { echo '算法B'; } } //定义上下文执行环境 class context { private $strategy; function __construct(strategy $s) { $this->strategy = $s; } function contextInterface() { $this->strategy->algorithmInterface(); } } //客户端调用不同算法 $strategyA = new concreteStrategyA(); $context = new context($strategyA); $context->contextInterface(); //算法A $strategyB = new concreteStrategyB(); $context = new context($strategyB); $context->contextInterface(); //算法B
好文章要分享:
https://zhuanlan.zhihu.com/p/105954533