设计模式之适配器

适配器模式(Adapter Pattern)将一个类的接口转换成客户所期待的另一个接口,使得原本由于接口不匹配而无法在一起工作的那些类能够在一起工作。

结构:(类的适配器模式)


(对象的适配器模式)



角色:

Target角色:这是客户所期待的接口。目标可以是具体的或抽象的类,也可以是接口。
Adaptee角色:需要适配的类。
Adapter角色:通过在内部包装一个Adaptee对象,把源接口转换成目标接口。

示例代码:

//  类适配器
 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();
   }
 }
 public class Client
 {  public static void Main(string[] args)
   {    // Create adapter and place a request
     ITarget t = new Adapter();
     t.Request();
   }
 }

// 对象适配器
 using System; 
 // "Target"
 class Target
 {  virtual public void Request()
   {    // Normal implementation goes here  }
 }
 // "Adapter"
 class Adapter : Target
 {  // Fields
   private Adaptee adaptee = new Adaptee(); 
   // Methods
   override public void Request()
   {    // Possibly do some data manipulation
     // and then call SpecificRequest
     adaptee.SpecificRequest();
   }
 }
 // "Adaptee"
 class Adaptee
 {  // Methods
   public void SpecificRequest()
   {    Console.WriteLine("Called SpecificRequest()" );  }
 } 
 public class Client
 {  public static void Main(string[] args)
   {    // Create adapter and place a request
     Target t = new Adapter();
     t.Request();
   }
 }
Adapter模式的要点:

Adapter模式可以实现得非常灵活,不必拘泥于GoF的两种结构。例如,完全可以将Adapter模式中的“现存对象”作为新的接口方法参数,来达到适配的目的。
Adapter模式本身要求我们尽可能地使用“面向接口的编程”风格,这样才能在后期很方便地适配。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值