首页 > 其他 > 详细

设计模式之GOF23适配器模式

时间:2019-08-10 10:07:48      阅读:76      评论:0      收藏:0      [点我收藏+]

结构型模式

核心作用:是从程序的结构上实现松耦合,从而可以扩大整体的 类结构,用来解决更大的问题

适配器模式adapter

实际生活中的例子:转换器

适配器的两种方式:

1,类适配器(继承)

/**需要适配的对象
 * @author 小帆敲代码
 *
 */
public class Adaptee {
  public void request() {
   System.out.println("can do something");
  }
}

/**
 *适配器(类适配器)
 * @author 小帆敲代码
 *
 */
public class Adapter extends Adaptee implements Target {
 @Override
 public void handleReq() {
   super.request();
 }
}
/**
 * 客户端
 * @author 小帆敲代码
 *
 */
public class Client {
  public void test(Target t) {
   t.handleReq();
  }
  public static void main(String[] args) {
   Client c=new Client();
   Target t=new Adapter();
   c.test(t);
  }
}
public interface Target {
  public void handleReq();
}
技术分享图片
2,对象适配器(组合)
/**需要适配的对象
 * @author 小帆敲代码
 *
 */
public class Adaptee {
  public void request() {
   System.out.println("can do something");
  }
}
/**
 *适配器(对象适配器)
 * @author 小帆敲代码
 *
 */
public class Adapter2 extends Adaptee implements Target {
 private Adaptee a;
 @Override
 public void handleReq() {
   a.request();
 }
 public Adapter2() {
  
 }
 public Adapter2(Adaptee a) {
  this.a=a;
 }
}
public class Client2 {
 public void test(Target t) {
  t.handleReq();
 }
 public static void main(String[] args) {
  Client c=new Client();
  Adaptee a=new Adaptee();
  Target t=new Adapter2(a);
  c.test(t);
 }
}
public interface Target {
  public void handleReq();
}
技术分享图片

设计模式之GOF23适配器模式

原文:https://www.cnblogs.com/code-fun/p/11330513.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!