适配器模式的作用:
将某个类的接口转换成客户期望的另一个接口表示,目的是消除由于接口不匹配所造成的类的兼容性问题。适配器模式的角色:
Adaptee,被适配者,需要被适配的类。
Target,目标类,即需要实现功能的接口或抽象类。
Adapter ,适配器,拥有目标类的功能,以及被适配者的功能。
适配器模式的类型:
类适配器,通过适配器继承被适配者实现对象适配器,通过适配器关联被适配者实现。类适配器通过适配器继承被适配者实现。
Adaptee,被适配者。
pulic class Adaptee{ public void method1(){ System.out.PRintln("this is method 1"); }}Target,目标接口。
public interface Target{ public void method2();}Adapter ,类适配器。
public class Adapter extends Adaptee implements Target{ @Override public void method2() { System.out.println("this is method 2"); }}具体调用如下:
Adapter adaoter= new Adapter();adater.method1();adater.method2();对象适配器通过适配器关联被适配者实现。
Adaptee 类、Target 接口代码同上。
新闻热点
疑难解答