第七章 为别人做嫁衣 --- 代理模式

  1. <?php
  2. class SchoolGirl
  3. {
  4. private $name;
  5. function __construct($name)
  6. {
  7. $this->name = $name;
  8. }
  9. public function getName()
  10. {
  11. return $this->name;
  12. }
  13. }
  14. // 代理接口
  15. interface GiveGift
  16. {
  17. public function GiveDolls();
  18. public function GiveFlowers();
  19. public function GiveChocolate();
  20. }
  21. // 代理实现送礼物接口
  22. class Proxy implements GiveGift
  23. {
  24. protected $pursuit;
  25. function __construct(SchoolGirl $girl)
  26. {
  27. $this->pursuit = new Pursuit($girl);
  28. }
  29. public function GiveDolls()
  30. {
  31. $this->pursuit->GiveDolls();
  32. }
  33. public function GiveFlowers()
  34. {
  35. $this->pursuit->GiveFlowers();
  36. }
  37. public function GiveChocolate()
  38. {
  39. $this->pursuit->GiveChocolate();
  40. }
  41. }
  42. // 追求者类实现送礼物接口
  43. class Pursuit implements GiveGift
  44. {
  45. protected $girl;
  46. function __construct(SchoolGirl $girl)
  47. {
  48. $this->girl = $girl;
  49. }
  50. public function GiveDolls()
  51. {
  52. echo $this->girl->getName()." 送你娃娃\n";
  53. }
  54. public function GiveFlowers()
  55. {
  56. echo $this->girl->getName()." 送你花\n";
  57. }
  58. public function GiveChocolate()
  59. {
  60. echo $this->girl->getName()." 送你巧克力\n";
  61. }
  62. }
  63. // 客户端代码
  64. $girl = new SchoolGirl('李梅');
  65. $proxy = new Proxy($girl);
  66. $proxy->GiveDolls();
  67. $proxy->GiveChocolate();
  68. $proxy->GiveFlowers();

总结:

代理模式,为其他对象提供一种代理以控制对这个对象的访问