php設計模式之命令鏈模式

來源:互聯網
上載者:User
命令鏈模式:

   命令鏈模式以鬆散耦合主題為基礎,發送訊息、命令和請求,或通過一組處理常式發送任意內容。每個處理常式都會自行判斷自己能否處理請求。如果可以,該請求被處理,進程停止。您可以為系統添加或移除處理常式,而不影響其他處理常式。

1.interface Validator

2.{

3. /**

4. * The method could have any parameters.

5. * @param mixed

6. * @return boolean

7. */

8. public function isValid($value);

9.}

10.

11./**

12. * ConcreteCommand.

13. */

14.class MoreThanZeroValidator implements Validator

15.{

16. public function isValid($value)

17. {

18. return $value > 0;

19. }

20.}

21.

22./**

23. * ConcreteCommand.

24. */

25.class EvenValidator implements Validator

26.{

27. public function isValid($value)

28. {

29. return $value % 2 == 0;

30. }

31.}

32.

33./**

34. * The Invoker. An implementation could store more than one

35. * Validator if needed.

36. */

37.class ArrayProcessor

38.{

39. protected $_rule;

40.

41. public function __construct (Validator $rule)

42. {

43. $this->_rule = $rule;

44. }

45.

46. public function process(array $numbers)

47. {

48. foreach ($numbers as $n) {

49. if ($this->_rule->IsValid($n)) {

50. echo $n, "\n";

51. }

52. }

53. }

54.}

55.

56.// Client code

57.$processor = new ArrayProcessor(new EvenValidator());

58.$processor->process(array(1, 20, 18, 5, 0, 31, 42));




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.