书中用打扮的代码阐释了这样情况下的写法:

    1. // 人
    2. class Person
    3. {
    4. private $name;
    5. function __construct($name)
    6. {
    7. $this->name = $name;
    8. }
    9. public function show()
    10. {
    11. echo "打扮".$this->name."\n";
    12. }
    13. }
    14. // 服饰类
    15. class Finery
    16. {
    17. protected $person;
    18. public function decorate($person)
    19. {
    20. $this->person = $person;
    21. }
    22. public function show()
    23. {
    24. if ($this->person != null)
    25. {
    26. $this->person->show();
    27. }
    28. }
    29. // 具体服饰类
    30. class TShirts extends Finery
    31. {
    32. public function show()
    33. {
    34. echo "大T恤\n";
    35. parent::show();
    36. }
    37. }
    38. class BigTrouser extends Finery
    39. {
    40. public function show()
    41. {
    42. echo "跨裤\n";
    43. parent::show();
    44. }
    45. }
    46. class Sneakers extends Finery
    47. {
    48. public function show()
    49. {
    50. echo "破球鞋\n";
    51. parent::show();
    52. }
    53. }
    54. class Suit extends Finery
    55. {
    56. public function show()
    57. parent::show();
    58. }
    59. }
    60. class Tie extends Finery
    61. {
    62. public function show()
    63. {
    64. echo "领带\n";
    65. parent::show();
    66. }
    67. }
    68. class LeatherShoes extends Finery
    69. {
    70. public function show()
    71. {
    72. echo "跨裤\n";
    73. parent::show();
    74. }
    75. }
    76. // 客户端代码
    77. $person = new Person("alex");
    78. $sneakers = new Sneakers();
    79. $bigTrouser = new BigTrouser();
    80. $tShirts = new TShirts();
    81. $sneakers->decorate($person);
    82. $bigTrouser->decorate($sneakers);
    83. $tShirts->show();

    总结

    装饰模式是为已有功能动态的添加更多功能的一种方式。

    当系统需要新功能的时候,是向旧的类中添加新的代码。这些新的代码通常装饰了原有类的核心职责或主要行为。

    装饰模式的优点就是把类中的装饰功能从类中搬移去除,这样可以简化原有的类。

    有效地把类的核心职责和装饰功能区分开了,而且可以去除相关类中的重复的装饰逻辑。

    下一章: