经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » 设计模式 » 查看文章
PHP设计模式—适配器模式
来源:cnblogs  作者:幽篁晓筑  时间:2020/11/9 16:08:07  对本文有异议

 

定义:

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

 

结构:

  • Target:目标接口,定义与客户端交互相关的接口,目标可以是具体的或抽象的类,也可以是接口。
  • Adaptee:源接口,需要适配的类。
  • Adapter:适配器,对 Adaptee 的接口与 Target 接口进行适配,通过在内部包装一个 Adaptee对象,把源接口转换成目标接口。
  • Client:客户端代码。

 

代码实例:

类适配器:

  1. /**
  2. * Target.php(目标接口)
  3. * Interface Target
  4. */
  5. interface Target
  6. {
  7. public function method1();
  8. public function method2();
  9. }
  10. /**
  11. * Adaptee.php(源接口)
  12. * Class Adaptee
  13. */
  14. class Adaptee
  15. {
  16. public function method1()
  17. {
  18. echo "Adaptee Method1<br/>\n";
  19. }
  20. }
  21. /**
  22. * Adapter.php(适配器)
  23. * Class Adapter
  24. */
  25. class Adapter extends Adaptee implements Target
  26. {
  27. public function method2()
  28. {
  29. // TODO: Implement method2() method.
  30. echo "Adapter Method2<br/>\n";
  31. }
  32. }
  33. // 客户端调用
  34. $adapter = new Adapter();
  35. $adapter->method1();
  36. $adapter->method2();

 

对象适配器:

  1. /**
  2. * Target.php(目标接口)
  3. * Interface Target
  4. */
  5. interface Target
  6. {
  7. public function method1();
  8. public function method2();
  9. }
  10. /**
  11. * Adaptee.php(源接口)
  12. * Class Adaptee
  13. */
  14. class Adaptee
  15. {
  16. public function method1()
  17. {
  18. echo "Adaptee Method1<br/>\n";
  19. }
  20. }
  21. /**
  22. * Adapter.php(适配器)
  23. * Class Adapter
  24. */
  25. class Adapter implements Target
  26. {
  27. private $adaptee;
  28. public function __construct(Adaptee $adaptee)
  29. {
  30. $this->adaptee = $adaptee;
  31. }
  32. public function method1()
  33. {
  34. // TODO: Implement method1() method.
  35. $this->adaptee->method1();
  36. }
  37. public function method2()
  38. {
  39. // TODO: Implement method2() method.
  40. echo "Adapter Method2<br/>\n";
  41. }
  42. }
  43. // 客户端调用
  44. $adapter = new Adapter(new Adaptee());
  45. $adapter->method1();
  46. $adapter->method2();

 

原文链接:http://www.cnblogs.com/woods1815/p/13853054.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号