1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
interface { public function doOperation($num1, $num2 ); }
class OperationAdd implements { public function doOperation($num1, $num2) { return $num1 + $num2; } }
class OperationSubstract implements { function doOperation( $num1 , $num2 ) { return $num1 - $num2; } }
class OperationMultiply implements { 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;
|
近期评论