首页 > 其他 > 详细

适配器模式

时间:2019-03-13 11:54:19      阅读:157      评论:0      收藏:0      [点我收藏+]

作为两个不兼容的接口之间的桥梁。

主要角色有目标(target)接口、适配者(Adaptee)、适配器(Adapter)

Target:

1 public interface Target {
2 
3     void targetMethod();
4 }

Adaptee:

1 public class Adaptee {
2 
3     public void adaptee() {
4         System.out.println("adaptee");
5     }
6 }

Adapter:

 1 public class Adapter implements Target {
 2 
 3     private Adaptee adaptee;
 4 
 5     public Adapter(Adaptee adaptee) {
 6         this.adaptee = adaptee;
 7     }
 8 
 9     @Override
10     public void targetMethod() {
11         adaptee.adaptee();
12     }
13 }

测试方法:

1 public class Main {
2 
3     public static void main(String[] args) {
4         Adaptee adaptee = new Adaptee();
5         Target adapter = new Adapter(adaptee);
6         adapter.targetMethod();
7     }
8 }

以上是对象适配器的写法,如果是类适配器,适配器可以选择直接继承适配者。

适合系统或者第三方组件二次开发的时候,新旧接口不一致的情况。

对类的适配器来说,更换适配器过程复杂。

 

适配器模式

原文:https://www.cnblogs.com/avalon-merlin/p/10521616.html

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