把一个类的接口变成客户端所期待的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作
/**
* 目标角色
*/
public interface Target {
public void operation1();
public void operation2();
}
/**
* 原角色
*/
public class Adaptee {
public void operation1(){
System.out.println("原角色的方法 operation1");
}
}
/**
* 适配器
*/
public class Adapter implements Target {
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
public void operation1() {
adaptee.operation1();
}
public void operation2() {
System.out.println("operation2");
}
}
/**
* 客户端
*/
public class Client {
public static void main(String[] args) {
Adaptee adaptee = new Adaptee();
Adapter adapter = new Adapter(adaptee);
Client client = new Client();
client.use(adapter);
}
public void use(Target target){
target.operation1();
}
}