阅读《研磨设计模式》笔记。之后若有所感,再补充。
适配器模式 的 目的:客户端需要的功能已经是实现好了,但是客户端使用的接口与实现类的类型不匹配,需要适配器来进行转换匹配。
示例代码:
适配器模式 的 目的:客户端需要的功能已经是实现好了,但是客户端使用的接口与实现类的类型不匹配,需要适配器来进行转换匹配。
示例代码:
/**
* @description 定义客户端使用的接口,与特定领域相关
* @author liuwei
* @date 2014-4-16
* @version 1.0
*/
public interface Target {
/**
* 示意方法,客户端请求处理的方法
*/
public void request();
}
/**
* @description已经存在的接口
* @author liuwei
* @date 2014-4-16
* @version 1.0
*/
public class Adaptee {
/**
* 示意方法,原本已经存在的方法
*/
public void specificRequest(){
System.out.println("adaptee: specificRequest");
}
}
/**
* @description
* @author liuwei
* @date 2014-4-16
* @version 1.0
*/
public class Adapter implements Target{
/**
* 持有需要被适配的接口对象
*/
private Adaptee adaptee;
public Adapter(Adaptee adaptee){
this.adaptee = adaptee;
}
/* (non-Javadoc)
* @see adapter.Target#request()
*/
@Override
public void request() {
//调用 Adaptee 的方法,进行适配
this.adaptee.specificRequest();
}
}
/**
* @description 使用适配器的客户端
* @author liuwei
* @date 2014-4-16
* @version 1.0
*/
public class Client {
public static void main(String[] strs){
//创建需要被适配的对象
Adaptee adaptee = new Adaptee();
//创建客户端需要调用的接口对象
Target target = new Adapter(adaptee);
//请求处理
target.request();
}
}