适配器模式

本文通过具体的代码示例介绍了适配器模式的概念及其应用。该模式主要用于将现有类的功能复用到新的接口标准中,使得原本不兼容的类可以协同工作。

     适配器的意图是复用现有对象的功能. 这个模式用的还是比较多的.

// Existing way requests are implemented
  class Adaptee { 
    // Provide full precision
    public double SpecificRequest (double a, double b) {
      return a/b;
    }
  }
  
  // Required standard for requests
  interface ITarget {
    // Rough estimate required
    string Request (int i);
  }
  
  // Implementing the required standard via the Adaptee
  class Adapter : Adaptee, ITarget {
    public string Request (int i) {
      return "Rough estimate is " + (int) Math.Round(SpecificRequest (i,3));
    }
  }

重新定义了一个Request方法,然后调用基类方法SpecificRequest (也可以不用继承,从内部实例化对象也可以,具体可灵活运用)

static void  Main () {
    // Showing the Adapteee in stand-alone mode
   Adaptee first = new Adaptee();
   Console.Write("Before the new standard\nPrecise reading: ");
   Console.WriteLine(first.SpecificRequest(5,3));
    
   // What the client really wants
   ITarget second = new Adapter();
   Console.WriteLine("\nMoving to the new standard");
   Console.WriteLine(second.Request(5));
   Console.ReadKey();
 }

其实模式这东西,只要掌握了面向对象,模式就自然运用出来了

转载于:https://www.cnblogs.com/Clingingboy/archive/2010/08/26/1809540.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值