适配器模式把一个类的接口变换成客户端所期待的另一种接口,从而使原本接口不匹配而无法在一起工作的两个类能够在一起工作。
二,类的Adapter模式的结构:
三,示例代码
/**
* 目标
*
* @author Salmon
*
*/
public interface Target {
public void request();
}
/**
* 源
*
* @author Salmon
*
*/
public class Adaptee {
public void specificRequest() {
System.out.println("Called SpecificRequest()");
}
}
/**
* 适配器
*
* @author Salmon
*
*/
public class Adapter extends Adaptee implements Target {
// Implements ITarget interface
public void request() {
// Possibly do some data manipulation
// and then call SpecificRequest
this.specificRequest();
}
}
/**
* 客户代码
*
* @author Salmon
*
*/
public class Client {
public static void Main(String[] args) {
// Create adapter and place a request
Target t = new Adapter();
t.request();
}
}
四,对象的Adapter模式的结构
目标(Target)角色:这是客户所期待的接口。目标可以是具体的或抽象的类,也可以是接口。
源(Adaptee)角色:需要适配的类。
适配器(Adapter)角色:通过在内部包装(Wrap)一个Adaptee对象,把源接口转换成目标接口。
五,示例代码
/**
* 目标接口
* @author Salmon
*
*/
public interface Target {
public void request();
}
/**
* 源
* @author Salmon
*
*/
public class Adaptee {
public void SpecificRequest() {
System.out.println("Called SpecificRequest()");
}
}
/**
* 适配器
* @author Salmon
*
*/
public class Adapter implements Target {
private Adaptee adaptee = new Adaptee();
public void request() {
// Possibly do some data manipulation
// and then call SpecificRequest
adaptee.SpecificRequest();
}
}
/**
* 客户端代码
*
* @author Salmon
*
*/
public class Client {
public static void main(String[] args) {
// Create adapter and place a request
Target t = new Adapter();
t.request();
}
}