定义:将一个类的接口转换为客户希望的另外一个接口。
举个例子
先熟悉一下适配器模板代码
客户希望的接口
//在客户端被使用的接口
public interface Target {
public void request();
}
现在存在的类
//已经存在的接口
public class Adaptee {
//示意方法
public void specificRequest()
{
}
}
将存在的类适配为客户希望使用的接口的适配器
public class Adapter implements Target {
//持有需要被适配的接口对象
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
super();
this.adaptee = adaptee;
}
@Override
public void request() {
adaptee.specificRequest();
}
}
用户使用它想要的接口
public class Client {
public static void main(String[] args) {
//创建需要被适配的对象
Adaptee adaptee = new Adaptee();
//创建客户端需要调用的接口对象
Target target = new Adapter(adaptee);
//请求处理
target.request();
}
}
举个例子套用模板加深适配器的理解
用户玩游戏f是跳k是蹲但是客户觉得操作别扭于是使用改键器改为a是跳d是蹲
用户最初使用的键盘方案
public class Action {
public void F()
{
System.out.println("我跳");
}
public void K()
{
System.out.println("我蹲");
}
}
用户不想使用这套想使用下面这套键盘方案
public interface Action2 {
public void A();
public void D();
}
我们通过改键器实现用户的需求(因为用户需求可以通过适配原方案实现这里的改键器就是适配器)
public class ChangeKey implements Action2{
private Action action ;
public ChangeKey(Action a) {
super();
this.action = a;
}
@Override
public void A() {
action.F();
}
@Override
public void D() {
action.K();
}
}
这样我们就实现了用户希望使用的新键位
编写测试类
public class Client {
public static void main(String[] args) {
Action a1 = new Action();
a1.F();
a1.K();
System.out.println("======用户觉得不舒服使用改建器=====");
Action2 a2 = new ChangeKey(a1);
a2.A();
a2.D();
}
}
输出:
参考资料:研磨设计模式,大话设计模式