[PHP] 命令模式 PHP设计模式 →→→→→进入此内容的聊天室

来自 , 2019-08-10, 写在 PHP, 查看 99 次.
URL http://www.code666.cn/view/ec8b57b0
  1. /**  
  2.  * The Command abstraction.  
  3.  * In this case the implementation must return a result,  
  4.  * sometimes it only has side effects.  
  5.  */
  6. interface Validator  
  7. {  
  8.     /**  
  9.      * The method could have any parameters.  
  10.      * @param mixed  
  11.      * @return boolean  
  12.      */
  13.     public function isValid($value);  
  14. }  
  15.  
  16. /**  
  17.  * ConcreteCommand.  
  18.  */
  19. class MoreThanZeroValidator implements Validator  
  20. {  
  21.     public function isValid($value)  
  22.     {  
  23.         return $value > 0;  
  24.     }  
  25. }  
  26.  
  27. /**  
  28.  * ConcreteCommand.  
  29.  */
  30. class EvenValidator implements Validator  
  31. {  
  32.     public function isValid($value)  
  33.     {  
  34.         return $value % 2 == 0;  
  35.     }  
  36. }  
  37.  
  38. /**  
  39.  * The Invoker. An implementation could store more than one  
  40.  * Validator if needed.  
  41.  */
  42. class ArrayProcessor  
  43. {  
  44.     protected $_rule;  
  45.  
  46.     public function __construct (Validator $rule)  
  47.     {  
  48.         $this->_rule = $rule;  
  49.     }  
  50.  
  51.     public function process(array $numbers)  
  52.     {  
  53.         foreach ($numbers as $n) {  
  54.             if ($this->_rule->IsValid($n)) {  
  55.                 echo $n, "\n";  
  56.             }  
  57.         }  
  58.     }  
  59. }  
  60.  
  61. // Client code  
  62. $processor = new ArrayProcessor(new EvenValidator());  
  63. $processor->process(array(1, 20, 18, 5, 0, 31, 42));

回复 "命令模式 PHP设计模式"

这儿你可以回复上面这条便签

captcha