设计模式之适配器模式(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();
}
}
}
运行结果:
特殊请求!
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();
}
}
}
运行结果:
特殊请求!
相关文章推荐
- 设计模式--适配器模式(Adapter)
- 设计模式之适配器模式(Adapter Pattern)
- 【设计模式】 适配器模式(Adapter Pattern)- 最易懂的设计模式解析
- 设计模式 适配器模式 Adapter
- 设计模式之(Adapter)适配器模式
- 设计模式之--适配器模式(adapter)
- Java设计模式(9)适配器模式(Adapter模式)
- 设计模式 - 适配器模式(adapter pattern) 具体解释
- java23种常用设计模式之适配器模式(Adapter)
- 设计模式之适配器模式(Adapter)
- Java设计模式之------(Adapter)适配器模式实现
- 设计模式(六):适配器模式Adapter(结构型模式)
- java设计模式之适配器模式Adapter
- 设计模式7--适配器模式(Adapter)
- 设计模式学习系列五:适配器模式(Adapter)
- Java:设计模式之适配器模式Adapter
- 设计模式(8)の结构型の适配器模式(Adapter)
- 【设计模式】学习笔记9:适配器模式(Adapter)
- 我所理解的设计模式(C++实现)——适配器模式(Adapter Pattern)
- 解读设计模式----适配器模式(Adapter Pattern),麻雀飞上枝头真能成凤凰?