Jackyfei

3.9策略模式

1.什么是策略模式?
        本质:面向借口编程。或者说策略模式是面向接口编程的最佳体现。
        他抽象的是不同的算法,或者说策略。
        比如税收,有个税和企业税。这是两种不同的算法,或者叫不同的策略。
 

 
2.利用接口实现策略模式:
 
//业务简述:税收分国税,企业税,个人税等等,不同税算法不同。
//策略模式本质就是面向接口编程,不同的算法可以理解为不同的策略
//抽象税收算法
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)
  {
        ITaxStrategy itax=new ITaxPerson();    TaxManager taxManager=new TaxManager(itax);
        //TaxManager和ITaxStrategy 的耦合,可以利用配置文件,依赖注入,表驱动等技术彻底解决之间的依赖关系。
      taxManager.GetTax(20000);
  }
}
 
 

3.利用委托实现策略模式:
 
        委托是一种引用方法的类型,委托本质是一个类,相当于类型安全的C++的函数指针。定义委托实际上就是定义一个行为接口。只要符合该行为接口的方法,都可以赋给委托。从这个角度来说,委托是方法级别的抽象,接口是对象级别的抽象,委托没有接口那样的强制要求实现,且针对静态方法。因此相对于接口,委托是一种更加开放的抽象。
        接下来,我们用委托来实现税收策略。
 
委托方法签名
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.前者是直接将方法封装为对象,后者则是直接对方法的操作。
2.前者可以被任何类实现,但是只能实现为公开的方法。
对于后者,只要某一个方法符合委托的方法签名,不管是静态方法,还是匿名函数或者Lambda表达式,都可以传递给委托。
3.从抽象的程度看,委托更彻底。
4.在.NET种,委托更多的是被用于事件,异步调用,回调方法当中,尤其是观察者模式中,使用委托更是事半功倍
 
posted @ 2014-03-24 15:26  张飞洪[厦门]  阅读(327)  评论(0编辑  收藏  举报