策略模式 发表于 2017-05-17 简单实现 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354interface Strategy{ public function doOperation($num1, $num2 );}class OperationAdd implements Strategy{ public function doOperation($num1, $num2) { return $num1 + $num2; }}class OperationSubstract implements Strategy{ function doOperation( $num1 , $num2 ) { return $num1 - $num2; }}class OperationMultiply implements Strategy{ public function doOperation( $num1 , $num2 ) { return $num1 * $num2; }}class Context{ private $strategy; public function __construct($strategy){ $this->strategy = $strategy; } public function executeStrategy($num1, $num2){ return $this->strategy->doOperation($num1, $num2); }}$context = new Context(new OperationAdd());echo ("10 + 5 = " . $context->executeStrategy(10, 5));echo PHP_EOL;$context = new Context(new OperationSubstract());echo ("10 - 5 = " . $context->executeStrategy(10, 5));echo PHP_EOL;$context = new Context(new OperationMultiply());echo ("10 * 5 = " . $context->executeStrategy(10, 5));echo PHP_EOL;