github地址:https://github.com/ZQCard/design_pattern
/** * 在策略模式(Strategy Pattern)中,一个类的行为或其算法可以在运行时更改。这种类型的设计模式属于行为型模式。 * 在策略模式中,我们创建表示各种策略的对象和一个行为随着策略对象改变而改变的 context 对象。策略对象改变 context 对象的执行算法。 */
(1)Strategy.class.php(策略抽象接口)
<?php namespace Strategy; interface Strategy { public function doOperation(int $num1, int $num2):int; }
(2)OperationAdd.class.php(加操作具体类)
<?php namespace Strategy; class OperationAdd implements Strategy { public function doOperation(int $num1, int $num2):int { return $num1 + $num2; } }
(3)OperationSubstract.class.php(减操作具体类)
<?php namespace Strategy;
class OperationSubstract implements Strategy
{
public function doOperation(int $num1, int $num2):int
{
return $num1 - $num2;
}
}
(4)OperationMultiply.class.php(乘操作具体类)
<?php namespace Strategy; class OperationMultiply implements Strategy { public function doOperation(int $num1, int $num2):int { return $num1 * $num2; } }
(5)strategy.php (客户端类)
<?php spl_autoload_register(function ($className){ $className = str_replace('\\','/',$className); include $className.".class.php"; }); use Strategy\Context; use Strategy\OperationAdd; use Strategy\OperationSubstract; use Strategy\OperationMultiply; $context = new Context(new OperationAdd()); echo $context->execute(10, 5); echo '<br/>'; $context = new Context(new OperationSubstract()); echo $context->execute(10, 5); echo '<br/>'; $context = new Context(new OperationMultiply()); echo $context->execute(10, 5); echo '<br/>';