适配器模式:把一个类的接口变成客户端所期待的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作。
动机:将一些现存的对象放在新的环境中时,即利用现有对象的良好实现,又能满足新的应用环境所要求的接口。
有两种适配器模式:
类适配器模式:适配器与适配者之间是继承(或实现)关系。
对象适配器模式:适配器与适配者之间是关联关系。
1.对象适配器模式:
客户端要调用的是request()方法,而适配者Adaptee没有该方法,但是客户端需要的功能specificRequest()方法能实现。
package computer;
public class Test {
public static void main(String[] args) {
Target target=new Adapter();
target.request();
}
}
//客户所期待的接口,可以是具体的类也可以是抽象的类或接口
class Target{
public void request() {
System.out.println("普通请求");
}
}
//需要适配的类
class Adaptee{
public void specificRequest() {
System.out.println("特殊请求");
}
}
//适配器类(通过在内部包装一个Adaptee对象,把源接口转换为目标接口)
class Adapter extends Target{
//简历私有的Adaptee对象,关联关系
private Adaptee adaptee=new Adaptee();
public void request() {
//把调用request()方法变为调用SpecificRequest()方法
adaptee.specificRequest();
}
}
2.类适配器模式:
package computer;
public class Test {
public static void main(String[] args) {
ITarget target=new Adapter();
target.request();
}
}
//客户所期待的接口
interface ITarget{
void request();
}
//需要适配的类
class Adaptee{
public void specificRequest() {
System.out.println("特殊请求");
}
}
//适配器类
class Adapter extends Adaptee implements ITarget{
public void request() {
//把调用request()方法变为调用SpecificRequest()方法
this.specificRequest();
}
}
应用场景:希望复用一些现存的类,但是接口又与复用环境不一致的情况。