把一个类的接口变成客户端所期待的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作
/**
* 目标角色
*/
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();
}
}
本文介绍了一种设计模式——适配器模式,该模式通过将一个类的接口转换为另一个接口,使原本不兼容的类可以协同工作。文章详细解释了适配器模式的实现方式,并提供了具体的代码示例。
1547

被折叠的 条评论
为什么被折叠?



