目标抽象角色(Target)
定义客户要用的特定领域接口
适配器(Adapter)
调用另一个接口,作为一个转换器
适配器(Adaptee)
定义一个接口,Adapater需要介入
客户端(Client)
协同对象符合Adapater适配器
插线板案例
![](https://images2015.cnblogs.com/blog/196558/201610/196558-20161022031324248-385975432.png)
两种类型的适配器模式
- 类适配器(采用继承的方法)
- 对象适配器(采用对象组合的方式)
![](https://images2015.cnblogs.com/blog/196558/201610/196558-20161022031324763-1080530601.png)
![](https://images2015.cnblogs.com/blog/196558/201610/196558-20161022031325248-552213699.png)
Target
interface Target
{
void MyOutPut();
}
Adaptee
interface Adaptee
{
void OutPut();
}
ConcreteAdaptee1
public class ConcreteAdaptee1 : Adaptee
{
public void OutPut()
{
Console.WriteLine("From ConcreteAdaptee");
}
}
ConcreteAdaptee2
class ConcreteAdaptee2 : Adaptee
{
public void OutPut()
{
Console.WriteLine("From ConcreteAdaptee2");
}
}
Adapter
class Adapter : Target
{
private Adaptee _adaptee; //必须要维护一个Adaptee类型的成员变量
public Adapter(Adaptee adaptee)
{
this._adaptee = adaptee;
}
public void MyOutPut()
{
this._adaptee.OutPut();
}
}
Client
class Client
{
static void Main(string[] args)
{
Target target = new Adapter(new ConcreteAdaptee1());
target.MyOutPut();
target = new Adapter(new ConcreteAdaptee2());
target.MyOutPut();
Console.Read();
}
}
![](https://images2015.cnblogs.com/blog/196558/201610/196558-20161022031325795-2062749405.png)
分析
![](https://images2015.cnblogs.com/blog/196558/201610/196558-20161022031326326-1693592834.png)