1. <?php
    2. /**
    3. * 设计模式之装饰器模式
    4. * 场景:在不改动类文件的前提上,对类进行功能上的扩展
    5. * 小黄牛
    6. */
    7. header("Content-type: text/html; charset=utf-8");
    8. /**
    9. * 接口 - 鞋
    10. */
    11. interface ShoesInterface{
    12. public function product();
    13. }
    14. /**
    15. * 创建 - 运动鞋模型
    16. */
    17. class ShoesSport implements ShoesInterface{
    18. public function product(){
    19. echo "生产一双球鞋";
    20. }
    21. }
    22. /**
    23. * 抽象 - 装饰器类
    24. */
    25. abstract class Decorator implements ShoesInterface{
    26. protected $shoes; // 模型的实例
    27. public function __construct($shoes){
    28. $this->shoes = $shoes;
    29. }
    30. # 生成方法
    31. public function product(){
    32. $this->shoes->product();
    33. }
    34. #定义装饰操作
    35. abstract public function decorate();
    36. }
    37. /**
    38. * 创建 - 贴标装饰器
    39. */
    40. class DecoratorBrand extends Decorator{
    41. public $_value; // 标签名
    42. /**
    43. * 生成操作
    44. */
    45. public function product(){
    46. $this->shoes->product();
    47. $this->decorate();
    48. }
    49. /**
    50. * 贴标操作
    51. */
    52. public function decorate(){
    53. echo "贴上{$this->_value}标志 <br/>";
    54. }
    55. }
    56. echo "未加装饰器之前:";
    57. # 生产运动鞋
    58. $shoesSport = new ShoesSport();
    59. $shoesSport->product();
    60. echo "<br/>";
    61. echo "加贴标装饰器:";
    62. # 初始化一个贴商标适配器
    63. $DecoratorBrand = new DecoratorBrand($shoesSport);
    64. # 写入标签名
    65. $DecoratorBrand->_value = 'nike';
    66. # 生产nike牌运动鞋
    67. $DecoratorBrand->product();

    浏览器输出!

    1. 未加装饰器之前:生产一双球鞋
    2. 加贴标装饰器:生产一双球鞋贴上nike标志

    装饰器模式

    1. 组件对象的接口:可以给这些对象动态的添加职责
    2. 所有装饰器的父类:需要定义一个与组件接口一致的接口,并持有一个Component对象,该对象其实就是被装饰的对象。
    3. 具体的装饰器类:实现具体要向被装饰对象添加的功能。用来装饰具体的组件对象或者另外一个具体的装饰器对象。

    于适配器模式的区别

    1. 适配器模式是用于对多个接口之间的链接与切换,而装饰器模式则是为了在不改动原类文件的前提下,对该类的功能进行外部扩展。