设计模式与实例代码:Adapter模式
2012-03-29 22:50
513 查看
定义/意图:将一个类的接口转换成客户希望的另外一个接口,使控制范围之外的一个原有类与我们期望的接口匹配。
问题:系统的数据和行为都正确,但接口不符:
解决方案:Adapter模式提供了具有所需要接口的包装类
参与者与协作者:Adapter改变了被适配类的接口,使得被适配类与Adapter的基类接口匹配。这样client就可以无分别的使用被适配的对象
效果:适配器模式使原有对象能够适应新的类结构,不受其接口限制
实现:将被适配类包含在Adapter类之中,Adapter与需要的接口匹配,调用其包含的类方法。
下面给出引模式的实现代码:
在Head First设计模式中有一个把鸭子装扮成火鸡的例子。在这里不再赘述。
在使用中有时所适配的对象可能并不能完全完成所需要的功能,这种情况下我们仍可以使用Adapter模式,这样已有类中的功能可以适配,而没有的功能可以在包装类中实现。
实际上,Adapter模式有两种类型,对象适配器和类适配器。我们上面看的例子和是对象适配器,Adapter中包含了一个Adaptee的对象。
类适配器方式采用多重继承的方式来实现,在类图中唯一的变动就是由Adapter继承自Adaptee。
问题:系统的数据和行为都正确,但接口不符:
解决方案:Adapter模式提供了具有所需要接口的包装类
参与者与协作者:Adapter改变了被适配类的接口,使得被适配类与Adapter的基类接口匹配。这样client就可以无分别的使用被适配的对象
效果:适配器模式使原有对象能够适应新的类结构,不受其接口限制
实现:将被适配类包含在Adapter类之中,Adapter与需要的接口匹配,调用其包含的类方法。
下面给出引模式的实现代码:
// Adapter pattern -- Structural example using System; namespace Adapter { /// <summary> /// MainApp startup class for Structural /// Adapter Design Pattern. /// </summary> class MainApp { /// <summary> /// Entry point into console application. /// </summary> static void Main() { // Create adapter and place a request Target target = new Adapter(); target.Request(); // Wait for user Console.ReadKey(); } } /// <summary> /// The 'Target' class /// </summary> class Target { public virtual void Request() { Console.WriteLine("Called Target Request()"); } } /// <summary> /// The 'Adapter' class /// </summary> class Adapter : Target { private Adaptee _adaptee = new Adaptee(); public override void Request() { // Possibly do some other work // and then call SpecificRequest _adaptee.SpecificRequest(); } } /// <summary> /// The 'Adaptee' class /// </summary> class Adaptee { public void SpecificRequest() { Console.WriteLine("Called SpecificRequest()"); } } }
在Head First设计模式中有一个把鸭子装扮成火鸡的例子。在这里不再赘述。
在使用中有时所适配的对象可能并不能完全完成所需要的功能,这种情况下我们仍可以使用Adapter模式,这样已有类中的功能可以适配,而没有的功能可以在包装类中实现。
实际上,Adapter模式有两种类型,对象适配器和类适配器。我们上面看的例子和是对象适配器,Adapter中包含了一个Adaptee的对象。
类适配器方式采用多重继承的方式来实现,在类图中唯一的变动就是由Adapter继承自Adaptee。
相关文章推荐
- [设计模式](四):建造者模式(Builder)与原型模式(Prototype)[含Kotlin深克隆实例代码]
- 设计模式与实例代码:Composite模式
- 设计模式与实例代码:Bridge模式
- PHP设计模式之观察者模式(Observer)详细介绍和代码实例
- 简单Java代码实例助你通俗易懂的理解什么是装饰(者)设计模式 (Decorator)
- (转)23种设计模式(4):建造者模式(实例代码并不怎么好)
- 最常用的Java设计之一 观察者模式 在android中的实例 ListView Adapter机制
- Java设计模式之装饰者模式详解和代码实例
- PHP设计模式之适配器模式代码实例
- 跟着实例学习设计模式(8)-适配器模式adapter(结构型)
- PHP设计模式之观察者模式(Observer)详细介绍和代码实例
- PHP设计模式之装饰者模式代码实例
- 设计模式之 Adapter实例
- 代码设计模式之适配器模式(Adapter)
- 145 php 设计模式代码和应用场景实例
- 23种设计模式java实例代码之装饰模式
- 设计模式实例与代码:Builder模式
- 设计模式与实例代码:单例模式
- 30. 代码实例-设计模式-回调方式使用模板方法
- Net设计模式实例之适配器模式(Adapter Pattern)