将一个类的接口转换成客户希望的另外一个接口。适配器模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
public interface Target {
public void request();
}
public class Adaptee {
public void existRequest() {
//
}
}
public class Adapter implement Target {
private Adaptee adaptee;
// get方法
// set方法
public void request() {
adaptee.existRequest();
}
}
在客户端可以用下面代码:
Adaptee adaptee = new Adaptee();
Target target = new Adapter();
target.setAdaptee(adaptee);
target.request();
建议使用双向适配器同时实现Target和Adaptee接口。
对象适配器:依赖于对象组合。
类适配器:通过继承来实现,java不允许多继承,因此java中不能实现标准的类适配器。可以通过
传递继承来实现。
适配器模式Adapter - 主要用来实现版本兼容
猜你喜欢
转载自katy1206.iteye.com/blog/2026111
今日推荐
周排行