适配器模式Adapter
有多个人使用一个接口A的方法,不同的人需要不同的方法实现,这时候就需要用到适配器模式
可以先使用一个类B实现该接口,但是其中的方法全不进行任何实现 ,接着谁需要里面的方法,就自己定义一个类C_X然后继承类B,覆盖其中的需要的方法。
适配器分为对象适配器和类适配器:对象适配器实现目标类的接口,依赖适配者类;类适配器继承适配者,并实现目标类的接口。
适配器模式的类图
适配器原理图
适配器模式的代码实现
// 定义客户端期待的接口
public class Target{
/// <summary>
/// 使用virtual修饰以便子类可以重写
/// </summary>
public virtual void Request(){
Console.WriteLine("This is a common request");
}
}
// 定义需要适配的类
public class Adaptee{
public void SpecificRequest(){
Console.WriteLine("This is a special request.");
}
}
/// 定义适配器
public class Adapter:Target{
// 建立一个私有的Adeptee对象
private Adaptee adaptee = new Adaptee();
/// <summary>
/// 通过重写,表面上调用Request()方法,变成了实际调用SpecificRequest()
/// </summary>
public override void Request(){
adaptee.SpecificRequest();
}
}
客户端代码
class Program{
static void Main(string[] args){
// 对客户端来说,调用的就是Target的Request()
Target target = new Adapter();
target.Request();
Console.Read();
}
}
将Map转为List的适配器实例
public class PeopleAdapter extends ArrayList<Object>{
private Map<?,?> map;
public PeopleAdapter(Map<?,?> map){
super();
this.map = map;
}
public int size(){
return map.size();
}
public Object get(int i) {
return map.get(i);
}
}
模式总结