代码改变世界

设计模式(五)--策略模式

2018-12-14 11:48  Caoxt  阅读(159)  评论(0编辑  收藏  举报

策略模式是对算法的包装,是把使用算法的责任和算法本身分割开来,委派给不同的对象管理。策略模式通常把一个系列的算法包装到一系列的策略类里面,作为一个抽象策略类的子类。用一句话来说,就是:“准备一组算法,并将每一个算法封装起来,使得它们可以互换”。

(一)为什么需要策略模式

1,在有多种算法相似的情况下,使用 if...else 所带来的复杂和难以维护。

2,利用面向对象的继承和多态机制,将多个算法解耦。避免类中出现太多的if-else语句

这个模式涉及到三个角色:

环境(Context)角色:持有一个Strategy的引用。

抽象策略(Strategy)角色:这是一个抽象角色,通常由一个接口或抽象类实现。此角色给出所有的具体策略类所需的接口。

具体策略(ConcreteStrategy)角色:包装了相关的算法或行为。

策略模式的优点
 算法可以自由切换;
 避免使用多重条件判断;
 扩展性良好。

策略模式的缺点:
 策略类会增多
 所有策略类都需要对外暴露

策略模式的适用场景:
 当一个系统中有许多类,它们之间的区别仅在于它们的行为,希望动态地让一个对象在许多行为中选择一种行为时;
 当一个系统需要动态地在几种算法中选择一种时;
 当一个对象有很多的行为,不想使用多重的条件选择语句来选择使用哪个行为时。

简单实例:加减乘除运算

<?php
abstract class math{
    abstract public function getVal($num1,$num2);
}

class jiaMath extends math{
    public function getVal($num1, $num2) {
        // TODO: Implement getVal() method.
        return $num1+$num2;
    }
}
class jianMath extends math{
    public function getVal($num1, $num2) {
        // TODO: Implement getVal() method.
        return $num1-$num2;
    }
}
class mulMath extends math{
    public function getVal($num1, $num2) {
        // TODO: Implement getVal() method.
        return $num1*$num2;
    }
}
class chuMath extends math{
    public function getVal($num1, $num2) {
        // TODO: Implement getVal() method.
        return $num1/$num2;
    }
}

class factory{
    public function __construct($oper){
        $classname=$oper.'Math';
        $this->obj=new $classname();
    }
    public function getVal($op1,$op2){
        echo $this->obj->getVal($op1,$op2);
    }
}

$obj=new factory('chu');
$obj->getVal(10,6);

详细查看:https://www.jianshu.com/p/7b7de81cdfbe