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

简介: 一.委托和异步调用:     先上代码:  public class AsyncClass {private List output=new List();public List OutPut { get { return output; } }public AsyncClass(...

一.委托和异步调用:

    先上代码:

   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]); 

  }

}

  

 

目录
相关文章
|
1月前
接口和抽象类的区别
接口和抽象类的区别
16 0
|
4月前
|
Java
抽象类和接口有什么区别?
抽象类和接口有什么区别?
|
12天前
|
Java
抽象类和接口的区别
抽象类和接口的区别
25 0
|
1月前
|
Java
22、接口与抽象类、匿名类的介绍
22、接口与抽象类、匿名类的介绍
23 0
|
8月前
|
设计模式 算法
抽象类应用模板方法模式和接口应用之策略设计模式
抽象类应用模板方法模式和接口应用之策略设计模式
38 0
|
8月前
接口和抽象类有什么区别
接口和抽象类有什么区别
46 0
|
9月前
|
Java C++
接口与抽象类的区别
接口与抽象类的区别
|
Java
第22篇:接口与抽象类、匿名类的介绍
📋 匿名类和局部类一样,都只能访问 final 或有效 final 的局部变量 📋 匿名类可以直接访问外部类中的所有成员(即使被声明为 private) 📋 匿名类只有在实例相关的代码块中使用,才可直接访问外部类中的实例成员 📋 匿名类不能自定义构造方法 📋 匿名类可以有初始化块
118 0
抽象类、接口的区别和相似点(一)
抽象类、接口的区别和相似点(一)
111 0
抽象类、接口的区别和相似点(一)