php 设计模式之 策略
1. 策略模式
策略模式,又称为政策模式,属于 行为型的设计模式
定义一系列的算法,把它们一个个封装起来,并且使它们可以相互替换。本模式使得算法可独立于使用它的客户而变化
工厂模式属于创建型模式,用来创建对象,返回new出来的对象。调用对象的方法是由客户端来决定
策略模式通过执行上下文,将要调用的函数的行为和算法封装成类
代码冗余和耦合度变低,每个策略模块完成对应的功能
2. 实列
interface Message {
public function send();
}
class BaiduYunMessage implements Message {
function send() {
echo '百度云发送信息!';
}
}
class MessageContext {
private $message;
public function __construct(Message $msg) {
$this->message = $msg;
}
public function SendMessage() {
$this->message->send();
}
}
$bdMsg = new BaiduYunMessage();
$msgCtx = new MessageContext($bdMsg);
$msgCtx->SendMessage();
3. 使用场景
- 电商网站中,根据年龄或者性别展示不同的商品

浙公网安备 33010602011771号