实现适配器模式的两种方式:类适配器模式和对象适配器模式。
Adaptee: 需适配的类。
Adapter: 适配器类。
ITarget: 目标接口。
类适配器模式:
class Adaptee
{
public void SpecialRequest()
{
Console.WriteLine("被适配器需要实现的功能");
}
}
interface ITarget
{
void Request();
}
class Adapter : Adaptee, ITarget
{
public void Request()
{
base.SpecialRequest();
}
}
Adapter类为什么要继承Adaptee类呢?因为Adaptee类的功能需要通过Adapter类实现。那为什么要实现ITarget接口?Adapter类需通过ITarget接口才能实现Adaptee类的功能。这样说起来很抽象,想想电源适配器。Adaptee类相当于插头,ITarget相当于不适配插头的插座,Adapter当然是适配器了。插头除了得先接上适配器,适配器也得插入插座,这样才能让插头通电。
对象适配器模式
class Adaptee
{
public void SpecialRequest()
{
Console.WriteLine("被适配器需要实现的功能");
}
}
interface ITarget
{
void Request();
}
class Adapter : ITarget
{
private Adaptee adaptee;
public Adapter(Adaptee adaptee)
{
this.adaptee = adaptee;
}
public void Request()
{
adaptee.SpecialRequest();
}
}
class Program
{
static void Main(string[] args)
{
Adaptee adaptee = new Adaptee();
ITarget adapter = new Adapter(adaptee);
adapter.Request();
}
}