• 委托之异步调用 、抽象方法、策略模式、接口


    一.委托和异步调用:

        先上代码:

       public class AsyncClass
    {
    private List<string> output=new List<string>();
    public List<string> OutPut { get { return output; } }

    public AsyncClass()
    {
    Timer solwTimer = new Timer(new TimerCallback(OnTimerCallBack), "slow", 2500, 2500);
    Timer fastTimer = new Timer(new TimerCallback(OnTimerCallBack), "fast", 2000, 2000);
    output.Add("mid");
    }

    private void OnTimerCallBack(object state)
    {
    output.Add(state.ToString());
    }
    }

      static void Main(string[] args)
      {
        AsyncClass asyncClass=new AsyncClass();
        System.Threading.Thread.Sleep(3000);
        Console.WriteLine(asyncClass.OutPut[0]);
        Console.WriteLine(asyncClass.OutPut[1]);
        Console.WriteLine(asyncClass.OutPut[2]);


        Console.Read();
        //Assert.AreEqual("slow", asyncClass.OutPut[0]);
        //Assert.AreEqual("fast", asyncClass.OutPut[1]);
        //Assert.AreEqual("mid", asyncClass.OutPut[1]);
    }



    按理应该先执行slow->fast->mid

    实际上不是这样。

    slow和fast都是异步调用,应该先走主流程mid,最后才是slow,然后fast。

    有图为证:

     二.委托的本质,委托的抽象级别,委托和接口关系

      委托是一种引用方法的类型,委托本质是一个,定义委托实际上就是定义一个行为接口。只要符合该行为接口的方法,都可以赋给委托。从这个角度来说,委托是方法级别的抽象。

      接口和委托均完成了对行为的抽象,但是二者实现的本质,却有面向对象和面向过程之分。

         异:

         (1)前者是直接将方法封装为对象,后者则是直接对方法的操作。
           (2)前者可以被任何类实现,但是只能实现为公开的方法。对于后者,只要某一个方法符合委托的方法签名,不管是静态方法,还是匿名函数或者Lambda表达式,都可以传递给委托。参考委托让冒泡排序的扩展更加优雅--开闭原则的使用

         (3)从抽象的程度看,委托更彻底。在.NET种,委托更多的是被用于事件,异步调用,回调方法当中,尤其是观察者模式中,使用委托更是事半功倍。

           (4)接口是对象级别的抽象,委托没有接口那样的强制要求实现,且针对静态方法。因此相对于接口,委托是一种更加开放的抽象。委托可以看成是方法的模板,有点类似类的模板-泛型(对类的抽象),而接口没有那层味道。

       同:委托和接口类似之处,都是对方法的抽象。

      三.委托和接口在策略模式中的使用

         第三部分是对第二部分的实例验证。直接上代码:

    此处例子参考<大话设计模式>这本书
    //业务简述:税收分国税,企业税,个人税等等,不同税算法不同。策略模式本质就是面向接口编程,不同的算法可以理解为不同的策略
    //抽象税收算法
    public interface ITaxStrategy
    {
      double Calculate(double income)
    }

    //个税
    public class ITaxPerson:ITaxStrategy
    {
      public double Calculate(double income)
      {
        return income*0.1;
      }
    }

    //企税
    public class ITaxEnterprice:ITaxStrategy
    {
      public double Calculate(double income)
      {
        return income*0.3;
      }
    }
    //…… 其他未来不确定的税收算法


    public class TaxManager
    {
      public ITaxStrategy _itax
      //接口作为参数,降低耦合,保证了不管未来是出现何种算法,保证这里的模块是稳定的;利用构造函数执行注入。
      public Taxmanager(ITaxStrategy itax)
      {
        _itax=itax;
      }

      public double GetTex(double income)
      {
        _itax.Calculate(income);
      }
    }

    public class Program
    {
      public static void Main(string[] args)
      {
        TaxManager taxManager=new TaxManager();
        taxManager.GetTax(20000);
      }
    }
    接下来,我们用委托来实现税收策略。
    //委托方法签名public delegate double TaxCalculateHandler(double income);public class Tax{
      
    //个税  
    public double TaxPersonCalculate(double income)  {    return income*0.1;  }
      //企税  
    publice double TaxEnterpriceCalculate(double income)  {    return income*0.3;  }
      //…… 其他未来不确定的税收算法
    }
    public class TaxManager{  
      private TaxCalculateHandler _delegateCal
    //委托作为参数,降低耦合,保证了不管未来是出现何种算法,保证这里的模块是稳定的;利用构造函数执行注入。
      public Taxmanager(TaxCalculateHandler itax)  
      {    
        this._delegateCal=itax;  
      }  
      public double GetTex(double income)  
      {    
        _delegateCal(income);  
      }
    }
    public class Program{  
      public static void Main(string[] args)  {    
        TaxManager taxManager=new TaxManager(Tax.TaxPersonCalculate);    
        taxManager.GetTax(1000);  
      }
    }

      对比以上两种方式,思路差不多,都有很好的可扩展性,至于选择哪一种,就看具体情况了。


    四.匿名方法对委托的代码优化

         注释掉的部分,是冗长部分,优化后代码量减少不少。

      //1.抽象出的操作方法,个人感觉有点像类的模板即泛型,所以从某一方面,不妨称委托为抽象出来的方法模板。
      public delegate void StrHelloHandler();
      //委托是对具体方法的抽象,他隔离了调用者和实际执行方法的关联

      public class AsyncDelegate {
        private List<string> output = new List<string>();
        public List<string> OutPut { get { return output; } }
        public AsyncDelegate() {
          //2.委托的异步调用,这里主流程先执行,后才从Hello执行到World;
          StrHelloHandler handler=null;
          //handler += new StrHelloHandler(Hello);
          //handler += new StrHelloHandler(Split);
          //handler += new StrHelloHandler(World);
          //采用匿名方法对以上代码进行优化
          handler += delegate { output.Add("Hello"); };
          handler += delegate { output.Add(","); };
          handler += delegate { output.Add("World"); };
          output.Add("你好,世界.");
          handler.Invoke();
        }

            

        //private void Hello()
        //{
        // message[0]= "Hello";
        //}
        //private void Split()
        //{
        // message[1] = ",";
        //}
        //private void World()
        //{
        // message[2] = "World";
        //}

    }

    
    

    public class Program
    {
      static void Main(string[] args)
      {
        //AsyncClass asyncClass=new AsyncClass();
        //System.Threading.Thread.Sleep(3000);

        AsyncDelegate asyncClass = new AsyncDelegate();

        Console.WriteLine(asyncClass.OutPut[0]);
        Console.WriteLine(asyncClass.OutPut[1]);
        Console.WriteLine(asyncClass.OutPut[2]);
        Console.WriteLine(asyncClass.OutPut[3]);

        Console.Read();
        //Assert.AreEqual("slow", asyncClass.OutPut[0]);
        //Assert.AreEqual("fast", asyncClass.OutPut[1]);
        //Assert.AreEqual("mid", asyncClass.OutPut[1]); 

      }

    }

      

    希望以上分享对你有所帮助,感谢您的捧场。
    作者: 张飞洪[厦门]
    QQ群: 共享交流群

    打赏支持

  • 相关阅读:
    SpringBoot系列之缓存使用教程
    Dubbo系列之常用配置用法简介
    SpringBoot系列之集成Dubbo的方式
    JavaScript系列之回调函数callback
    JavaScript系列之事件冒泡机制简介
    Oracle基础之保留字和关键字
    Oracle调优之no_unnest和unnest用法简介
    InnoSetup 以命令行自动编译打包
    InnoSetup 脚本打包及管理员权限设置
    C# 获取系统当前IE版本号
  • 原文地址:https://www.cnblogs.com/jackyfei/p/dele.html
Copyright © 2020-2023  润新知