结构模式描述如何将类或者对象结合在一起形成更大的结构,结构模式描述两种不同的东西:类与类的实例,所以结构模式可分为类的结构模式和对象的结构模式。
适配器模式把一个类的接口变换成客户端所期待的另一种接口,从而使原本接口不匹配而无法再一起工作的两个类能够在一起工作。
目标角色:这是客户所期待的接口,因为c#不支持多继承,所以Target必须是接口,不可以是类。
源角色:需要适配的类。
适配器角色:把源接口转换成目标接口。
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Generic;
using System.Text;
namespace Simple_Factory
{
interface ITarget
{
void Request();
}
{
interface ITarget
{
void Request();
}
class Adaptee
{
public void SpecificRequest()
{
Console.WriteLine("Called SpecificRequest()");
}
}
{
public void SpecificRequest()
{
Console.WriteLine("Called SpecificRequest()");
}
}
class Adapter:Adaptee,ITarget
{
public void Request()
{
this.SpecificRequest();
}
}
{
public void Request()
{
this.SpecificRequest();
}
}
public class Client
{
public static void Main()
{
ITarget t = new Adapter();
t.Request();
}
}
}
{
public static void Main()
{
ITarget t = new Adapter();
t.Request();
}
}
}
对象的Adapter模式的结构:
目标角色:这是客户所期待的接口,目标可以是具体的或抽象的类,也可以是接口。
源角色:需要适配的类。
适配器角色:通过在内部包装一个Adaptee对象,把源接口转换成目标接口。
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Generic;
using System.Text;
namespace Simple_Factory
{
class Target
{
virtual public void Request()
{ }
}
{
class Target
{
virtual public void Request()
{ }
}
class Adaptee
{
public void SpecificRequest()
{
Console.WriteLine("Called SpecificRequest()");
}
}
{
public void SpecificRequest()
{
Console.WriteLine("Called SpecificRequest()");
}
}
class Adapter : Target
{
private Adaptee adaptee = new Adaptee();
{
private Adaptee adaptee = new Adaptee();
public override void Request()
{
adaptee.SpecificRequest();
}
}
{
adaptee.SpecificRequest();
}
}
class AdapterObj
{
Target t = new Target();
t.Request();
}
}
{
Target t = new Target();
t.Request();
}
}
在什么情况下使用适配器模式
1,系统需要使用现有的类,而此类的接口不符合系统的需要。
2,想要建立一个可以重复使用的类,用于与一些彼此之间没有太大关联的一些类,包括一些能在将来引进的类一起工作,这些源类不一定有很复杂的接口。
3,在设计里,需要改变多个已有子类的接口,如果使用类的适配器模式,就要针对每一个子类做一个适配器,而这不太实际。