1、结构型设计模式
2、适配器模式
3、类适配器
4、对象适配器

  • 适配器模式
  • 代理模式
  • 桥接模式
  • 装饰模式
  • 组合模式
  • 外观模式
  • 享元模式

适配器模式(Adapter Pattern)是作为两个不兼容的接口之间的桥梁。这种类型的设计模式属于结构型模式,它结合了两个独立接口的功能。

这种模式涉及到一个单一的类,该类负责加入独立的或不兼容的接口功能。举个真实的例子,读卡器是作为内存卡和笔记本之间的适配器。您将内存卡插入读卡器,再将读卡器插入笔记本,这样就可以通过笔记本来读取内存卡。

  1. package com.xgp.company.结构性模式.第一种_适配器模式;
  2. /**
  3. * 要被适配的类(网线)
  4. */
  5. public class Adaptee {
  6. public void request() {
  7. System.out.println("连接网线上网!");
  8. }
  9. }
  1. package com.xgp.company.结构性模式.第一种_适配器模式;
  2. /**
  3. * 客户端类:想上网,插不上网线
  4. */
  5. public class Computer {
  6. //我们的电脑需要连接上转接器才能上网
  7. public void net(NetToUsb adapter) {
  8. //上网的具体实现,找一个转接头
  9. adapter.handleRequest();
  10. }
  11. public static void main(String[] args) {
  12. //电脑,适配器,网线
  13. Computer computer = new Computer();
  14. Adapter adapter = new Adapter();
  15. // Adaptee adaptee = new Adaptee();
  16. computer.net(adapter);
  17. }
  18. }
  1. package com.xgp.company.结构性模式.第一种_适配器模式;
  2. /**
  3. * 接口转换器的抽像实现
  4. */
  5. public interface NetToUsb {
  6. //作用:处理请求(网 => usb)
  7. public void handleRequest();
  8. }
  1. package com.xgp.company.结构性模式.第一种_适配器模式;
  2. /**
  3. * 1、继承方式(类适配器)
  4. * 2、组合(对象适配器:常用)
  5. */
  6. /**
  7. * 适配器:需要连接usb和网线
  8. */
  9. public class Adapter extends Adaptee implements NetToUsb {
  10. @Override
  11. public void handleRequest() {
  12. //可以上网了
  13. super.request();
  14. }
  15. }
  1. 连接网线上网!
  1. package com.xgp.company.结构性模式.第二种_适配器模式;
  2. /**
  3. * 1、继承方式(类适配器)
  4. * 2、组合(对象适配器:常用)
  5. */
  6. /**
  7. * 适配器:需要连接usb和网线
  8. */
  9. public class Adapter implements NetToUsb {
  10. private Adaptee adaptee;
  11. public Adapter(Adaptee adaptee) {
  12. this.adaptee = adaptee;
  13. }
  14. @Override
  15. public void handleRequest() {
  16. //可以上网了
  17. adaptee.request();
  18. }
  19. }
  1. package com.xgp.company.结构性模式.第二种_适配器模式;
  2. /**
  3. * 客户端类:想上网,插不上网线
  4. */
  5. public class Computer {
  6. //我们的电脑需要连接上转接器才能上网
  7. public void net(NetToUsb adapter) {
  8. //上网的具体实现,找一个转接头
  9. adapter.handleRequest();
  10. }
  11. public static void main(String[] args) {
  12. //电脑,适配器,网线
  13. Computer computer = new Computer();
  14. Adaptee adaptee = new Adaptee();
  15. Adapter adapter = new Adapter(adaptee);
  16. computer.net(adapter);
  17. }
  18. }
  1. 连接网线上网!

版权声明:本文为xgp123原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/xgp123/p/12306674.html