当前位置:Gxlcms > PHP教程 > PHP设计模式之装饰模式

PHP设计模式之装饰模式

时间:2021-07-01 10:21:17 帮助过:16人阅读

这篇文章介绍的内容是关于PHP设计模式之 装饰模式 ,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下

装饰模式(Decorator)属于结构型模式之一,定义:动态地给一个对象增加一些额外的职责。

在我们生活中最为普遍的例子就是在玩游戏的时候随时伴随着人物角色的装备,皮肤。我相信不管男生女生,玩游戏的都买过吧。

其中最常见的就是一些游戏开发商,通过去做一些装备,例如武器,衣服,鞋子,戒指等等,来吸引玩家购买,穿在身上不仅好看,还带有额外属性。

这个例子是典型装饰器模式的应用,特点是在不影响其他类的情况下动态添加其它具体装备类

  1. <?php
  2. /** 构件接口类
  3. * interface IComponent
  4. */
  5. interface IComponent
  6. {
  7. function Display();
  8. }
  9. /** 人物类
  10. * Person
  11. */
  12. Class Person implements IComponent
  13. {
  14. private $name;
  15. function __construct($name)
  16. {
  17. $this->name = $name;
  18. }
  19. function Display()
  20. {
  21. echo "{$this->name}当前装备:";
  22. }
  23. }
  24. /** 装备类
  25. * Equipment
  26. */
  27. Class Equipment implements IComponent
  28. {
  29. protected $component;
  30. function Decorator(IComponent $component)
  31. {
  32. // 动态添加
  33. $this->component = $component;
  34. }
  35. function Display()
  36. {
  37. if(!empty($this->component)){
  38. $this->component->Display();
  39. }
  40. }
  41. }
  42. /** 具体装备 武器类
  43. * Weapon
  44. */
  45. Class Weapon extends Equipment
  46. {
  47. function Display(){
  48. parent::Display();
  49. echo "龙泉剑 ";
  50. }
  51. }
  52. /** 具体装备 戒指类
  53. * Ring
  54. */
  55. Class Ring extends Equipment
  56. {
  57. function Display(){
  58. parent::Display();
  59. echo "复活戒指 ";
  60. }
  61. }
  62. /** 具体装备 鞋子类
  63. * Shoes
  64. */
  65. Class Shoes extends Equipment
  66. {
  67. function Display(){
  68. parent::Display();
  69. echo "御风履 ";
  70. }
  71. }
  72. // 如果需要可以继续添加具体的装备 腰带 裤子 手镯
  1. <?php
  2. // 装饰器模式 index.php
  3. header("Content-Type:text/html;charset=utf-8");
  4. require_once "Decorator.php";
  5. // 创建人物
  6. $people = new Person("战士");
  7. // 武器
  8. $Weapon = new Weapon();
  9. // 戒指
  10. $Ring = new Ring();
  11. // 鞋子
  12. $Shoes = new Shoes();
  13. // 动态添加函数
  14. $Weapon->Decorator($people);
  15. $Ring->Decorator($Weapon);
  16. $Shoes->Decorator($Ring);
  17. // 显示
  18. $Shoes->Display();



输出结果:


  1. 战士当前装备:龙泉剑 复活戒指 御风履

相关推荐:

PHP设计模式之 组合模式

PHP设计模式之 桥接模式

PHP设计模式之 适配器模式

以上就是PHP设计模式之 装饰模式的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行