分离「策略」并使他们之间能互相快速切换。此外,这种模式是一种不错的继承替代方案(替代使用扩展抽象类的方式)。
例子计算器的设计
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();
}
}
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的艺术编程
链接:https://www.jianshu.com/p/89a64a92c0bb



