PHP设计模式-策略模式

策略模式

用途

分离「策略」并使他们之间能互相快速切换。此外,这种模式是一种不错的继承替代方案(替代使用扩展抽象类的方式)。

例子

  • 计算器的设计

代码

  • MathStrategy.php
namespace Strategy;


interface MathStrategy
{
    public function calc(int $num1, int $num2);
}
  • MathAdd.php
namespace Strategy;


class MathAdd implements MathStrategy
{
    public function calc(int $num1, int $num2): int
    {
        return $num1 + $num2;
    }
}
  • MathSub.php
namespace Strategy;


class MathSub implements MathStrategy
{
    public function calc(int $num1, int $num2): int
    {
        return $num1 - $num2;
    }
}
  • Computer.php
namespace Strategy;


class Computer
{
    public $math_class;

    public function __construct(int $type)
    {
        if ($type == 1) {
            $this->math_class = new MathAdd();
        } elseif ($type == 2) {
            $this->math_class = new MathSub();
        }
    }

    /**
     * 返回结构
     * @param int $num1
     * @param int $num2
     * @return int
     */
    public function getResult(int $num1, int $num2): int
    {
        if ($this->math_class === null) echo '对象为空';
        return $this->math_class->calc($num1, $num2);
    }
}
  • 实施调用
getResult(1,4);

echo '
'; $class2 = new Computer(2); echo $class2->getResult(2, 6);

总结

  • 工厂模式和策略模式的CML图片是相似的,他们区别在于,工厂模式是我们可以直接拿到对象进行操作;策略模式我们拿到的是对象的封装对象。

你可能感兴趣的:(PHP设计模式-策略模式)