名称 |
Adapter
|
结构 |
|
意图 |
将一个类的接口转换成客户希望的另外一个接口。A d a p t e r 模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。 |
适用性 |
- 你想使用一个已经存在的类,而它的接口不符合你的需求。
- 你想创建一个可以复用的类,该类可以与其他不相关的类或不可预见的类(即那些接口可能不一定兼容的类)协同工作。
- (仅适用于对象A d a p t e r )你想使用一些已经存在的子类,但是不可能对每一个都进行子类化以匹配它们的接口。对象适配器可以适配它的父类接口。
|
|
|
Code Example
OurAdapter聚集了FrameworkXTraget 和FrameworkYTarget的功能.
namespace Adapter_DesignPattern


{
using System;

class FrameworkXTarget

{
virtual public void SomeRequest(int x)

{
// normal implementation of SomeRequest goes here
}
}

class FrameworkYAdaptee

{
public void QuiteADifferentRequest(string str)

{
Console.WriteLine("QuiteADifferentRequest = {0}", str);
}
}

class OurAdapter : FrameworkXTarget

{
private FrameworkYAdaptee adaptee = new FrameworkYAdaptee();
override public void SomeRequest(int a)

{
string b;
b = a.ToString();
adaptee.QuiteADifferentRequest(b);
}
}


/**//// <summary>
/// Summary description for Client.
/// </summary>
public class Client

{
void GenericClientCode(FrameworkXTarget x)

{
// We assume this function contains client-side code that only
// knows about FrameworkXTarget.
x.SomeRequest(4);
// other calls to FrameworkX go here
// 
}
public static int Main(string[] args)

{
Client c = new Client();
FrameworkXTarget x = new OurAdapter();
c.GenericClientCode(x);
return 0;
}
}
}

通过继承Target和成员Adaptee 的适配方式,使Adapter 最终满足我们的需要!
// Adapter pattern -- Structural example


using System;

namespace DoFactory.GangOfFour.Adapter.Structural


{

// Mainapp test application

class MainApp

{
static void Main()

{
// Create adapter and place a request
Target target = new Adapter();
target.Request();

// Wait for user
Console.Read();
}
}

// "Target"

class Target

{
public virtual void Request()

{
Console.WriteLine("Called Target Request()");
}
}

// "Adapter"

class Adapter : Target

{
private Adaptee adaptee = new Adaptee();

public override void Request()

{
// Possibly do some other work
// and then call SpecificRequest
adaptee.SpecificRequest();
}
}

// "Adaptee"

class Adaptee

{
public void SpecificRequest()

{
Console.WriteLine("Called SpecificRequest()");
}
}
}

上面例子可以认为是
对象的Adapter模式, 因为target为一个实际的类,不是一个接口
以下为
类的Adapter设计模式: 因为target 为一个接口,又接口规范,且没有实例成员
// Class Adapter pattern -- Structural example
using System;

// "ITarget"
interface ITarget


{
// Methods
void Request();
}

// "Adaptee"
class Adaptee


{
// Methods
public void SpecificRequest()

{
Console.WriteLine("Called SpecificRequest()" );
}
}

// "Adapter"
class Adapter : Adaptee, ITarget


{
// Implements ITarget interface
public void Request()

{
// Possibly do some data manipulation
// and then call SpecificRequest
this.SpecificRequest();
}
}


/**//**//**//// <summary>
/// Client test
/// </summary>
public class Client


{
public static void Main(string[] args)

{
// Create adapter and place a request
ITarget t = new Adapter();
t.Request();
}
} 总结: 类适配器比对象适配器更好
类适配器提供了接口规范,
但是对象适配器没有,如果target改变接口的话,adaper可能没有跟着改变,最后导致error.也又可能会错用target里的实例成员.