适配器模式
将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以在一起工作。
适配器模式的二种实现方式
1、类的适配器模式
2、对象的适配器模式
1、类的适配器模式
- 目标接口(Target):客户所期待的接口。目标可以是具体的或抽象的类,也可以是接口。
- 需要适配的类(Adaptee):需要适配的类或适配者类。
- 适配器(Adapter):通过包装一个需要适配的对象,把原接口转换成目标接口。
代码实现
// 已存在的、具有特殊功能、但不符合我们既有的标准接口的类
class Adaptee {
public void specificRequest() {
System.out.println("被适配类具有 特殊功能...");
}
}
// 目标接口,或称为标准接口
interface Target {
public void request();
}
// 具体目标类,只提供普通功能
class ConcreteTarget implements Target {
public void request() {
System.out.println("普通类 具有 普通功能...");
}
}
// 适配器类,继承了被适配类,同时实现标准接口
class Adapter extends Adaptee implements Target{
public void request() {
super.specificRequest();
}
}
// 测试类public class Client {
public static void main(String[] args) {
// 使用普通功能类
Target concreteTarget = new ConcreteTarget();
concreteTarget.request();
// 使用特殊功能类,即适配类
Target adapter = new Adapter();
adapter.request();
}
}
运行结果:
普通类 具有 普通功能...
被适配类具有 特殊功能...
2、对象的适配器模式
代码实现
// 已存在的、具有特殊功能、但不符合我们既有的标准接口的类
public class Adaptee {
public void specificRequest() {
System.out.println("被适配类具有 特殊功能...");
}
}
// 目标接口,或称为标准接口
public interface Target {
public void request();
}
// 具体目标类,只提供普通功能
public class Adapter implements Target {
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adapte e= adaptee;
}
@Override
public void request() {
adaptee.specificRequest();
}
}
// 测试类public class Client {
public class Main {
public static void main(String[] args) {
Adaptee a = new Adaptee();
Target t = new Adapter(a);
t.request();
}
}
输出
被适配类具有 特殊功能...