• 第十七章 在NBA我需要翻译 --- 适配器模式

    第十七章 在NBA我需要翻译 --- 适配器模式

    1. <?php
    2. //篮球翻译适配器
    3. abstract class Player
    4. {
    5. protected $name;
    6. function __construct($name)
    7. {
    8. $this->name = $name;
    9. }
    10. abstract public function Attack();
    11. abstract public function Defense();
    12. }
    13. //前锋
    14. class Forwards extends Player
    15. {
    16. public function Attack()
    17. {
    18. echo "前锋:".$this->name." 进攻\n";
    19. }
    20. public function Defense()
    21. {
    22. echo "前锋:".$this->name." 防守\n";
    23. }
    24. }
    25. //中锋
    26. class Center extends Player
    27. {
    28. function __construct()
    29. {
    30. parent::__construct();
    31. }
    32. public function Attack()
    33. {
    34. echo "中锋:".$this->name." 进攻\n";
    35. }
    36. public function Defense()
    37. {
    38. echo "中锋:".$this->name." 防守\n";
    39. }
    40. }
    41. //外籍中锋
    42. class ForeignCenter
    43. {
    44. private $name;
    45. public function setName($name)
    46. {
    47. $this->name = $name;
    48. }
    49. public function getName()
    50. {
    51. return $this->name;
    52. }
    53. public function 进攻()
    54. {
    55. echo "外籍中锋:".$this->name." 进攻\n";
    56. }
    57. public function 防守()
    58. {
    59. echo "外籍中锋:".$this->name." 防守\n";
    60. }
    61. }
    62. //翻译者
    63. class Translator extends Player
    64. {
    65. private $foreignCenter;
    66. function __construct($name)
    67. {
    68. $this->foreignCenter = new ForeignCenter();
    69. $this->foreignCenter->setName($name);
    70. }
    71. public function Attack()
    72. {
    73. $this->foreignCenter->进攻();
    74. }
    75. public function Defense()
    76. {
    77. $this->foreignCenter->防守();
    78. }
    79. }
    80. // 客户端代码
    81. $forwards = new Forwards("巴蒂尔");
    82. $forwards->Attack();
    83. $forwards->Defense();
    84. $translator = new Translator("姚明");
    85. $translator->Attack();
    86. $translator->Defense();

    总结:

    适配器模式,将一个类的接口转化成客户希望的另外一个接口。适配器模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。

    系统的数据和行为都正确,但接口不符时,我们应该考虑用适配器,目的是使控制范围之外的一个原有对象与某个接口匹配。适配器模式主要应用于希望复用一些现存的类。但是接口又与复用环境要求不一致的情况。

    两个类所做的事情相同或相似,但是具有不同的接口时要使用它。

    在双方都不太容易修改的时候再使用适配器模式适配。

    上一章:第十六章 无尽加班何时休 --- 状态模式

    下一章:第十八章 如果再回到从前 --- 备忘录模式