把一個類的接口變成客戶端所期待的另一種接口,從而使原本因接口不匹配而無法在一起工作的兩個類能夠在一起工作
/**
* 目標角色
*/
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();
}
}