您的位置:首页 > 其它

设计模式之适配器模式(Adapter)

2014-03-28 14:08 288 查看
适配器模式(Adapter):将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作哪些类可以一起工作。
Target类:客户所期待的接口。目标可以是具体的或抽象的类。
Adaptee:需求适配的类
Adapter:通过在内部包装一个Adaptee对象,把源接口转换成目标接口需要使用一个已经存在的类,但如果它的接口,也就是它的方法和你的要求不相同时,两个类所做的事情相同或相似,但是具有不同的接口时要使用它。

Adapter1.cs




代码

using System;
using System.Collections.Generic;
using System.Text;

//适配器模式(Adapter):将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于
//接口不兼容而不能一起工作哪些类可以一起工作。
//Target类:客户所期待的接口。目标可以是具体的或抽象的类。
//Adaptee:需求适配的类
//Adapter:通过在内部包装一个Adaptee对象,把源接口转换成目标接口
//需要使用一个已经存在的类,但如果它的接口,也就是它的方法和你的要求不相同时,两个类所做的
//事情相同或相似,但是具有不同的接口时要使用它。
namespace Adapter
{
class Adapter1
{
}

//Target
class Target
{
public virtual void Request()
{
Console.WriteLine("普通请求!");
}
}
//Adaptee
class Adaptee
{
public void SpecificRequest()
{
Console.WriteLine("特殊请求!");
}
}
//Adapter
class Adapter : Target
{
private Adaptee adaptee = new Adaptee();//建立私有Adaptee对象

public override void Request()
{
adaptee.SpecificRequest();
}
//把表面上调用Request()方法编程实际调用SpecificRequest()
}
}

Program.cs




代码

using System;
using System.Collections.Generic;
using System.Text;

namespace Adapter
{
class Program
{
static void Main(string[] args)
{
Target target = new Adapter();
target.Request();

Console.Read();
}
}
}

 

运行结果:

特殊请求!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: