设计模式之策略模式学习

设计模式之策略模式学习

  

  

   

  策略模式(Strategy):它定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。

                                                                                                     --《HeadFirst设计模式》

 

  一般来说这些算法完成的工作都是一样的,只是它们的实现不一样而已,通过策略模式可以定义一个公共的接口去调用不同的算法类,从而降低了算法类和调用算法类的耦合度。

 

 

关键字:策略模式,接口,抽象类,继承

  

  

 

 

1        策略模式分析

       策略模式是一种定义一系列算法的方法,定义一个公共的接口,然后使用不同的算法类实现不同的算法。 应用场合:只要在分析过程中听到需要在不同时间应用不同的业务规则,就可以考虑使用策略模式处理这种变化的可能性。

  优点:通过抽象出公共的接口,从而降低算法类和调用算法类的耦合度(降低耦合度),每个算法都有自己的类,从而方便了每个算法类的单元测试。

  不足:我们在策略类里面都直接实例化了各种算法的类,这大大提高了策略类和算法类的耦合度,而且每当我们修改策略类的时候我们都要重新编译程序(修改方法:反射)。

 

                              

  

1使用策略模式UML

  

  

  

 

 

2    代码

 

 

复制代码
    
class StrategyA : Strategy { public override void AlgorithmInterface() { Console.WriteLine( " 算法A实现 " ); } }
复制代码

 

 

 

 

 

 

复制代码
    
class StrategyB : Strategy { public override void AlgorithmInterface() { Console.WriteLine( " 算法B实现 " ); } }
复制代码

 

 

 

 

 

 

 

 

复制代码
    
class StrategyC : Strategy { public override void AlgorithmInterface() { Console.WriteLine( " 算法C实现 " ); } }
复制代码

 

 

 

 

复制代码
    
class Context { private Strategy strategy = null ; public Context( string type) { switch (type) { case " A " : this .strategy = new StrategyA(); // instance the object break ; case " B " : this .strategy = new StrategyB(); break ; case " C " : this .strategy = new StrategyC(); break ; } } public void ContextInterface() { strategy.AlgorithmInterface(); } }
复制代码

 

 

 

 

3        优化

 

大家可能已经发现我是通过在策略类(Context)中实例化算法类的,这样加大了策略类和算法类之间的耦合度,好现在我就使用反射来解决这个问题。

首先我们要在项目中心机一个App.config文件然后我们只需在里面设置好要实例化的类的命名空间就好了。

接下来就像修改策略类(Context)的代码,这里我们是使用反射实例化算法类,使用泛型的优点就是每当我们调用不到的算法只需修改配置文件就OK了,不用重新编译程序(前提是算法类已经存在只是以前没有调用它)。

 

 

修改Context类之后的代码:

 

复制代码
    
class Context { private Strategy strategy = null ; private static readonly string path = ConfigurationManager.AppSettings[ " Strategy " ]; string className = string .Empty; public Context( string type) { switch (type) { case " A " : // this.strategy = new StrategyA(); // instance the object className = path + " .StrategyA " ; this .strategy = (StrategyModel.StrategyA)Assembly.Load(path).CreateInstance(className); break ; case " B " : // this.strategy = new StrategyB(); className = path + " .StrategyB " ; this .strategy = (StrategyModel.StrategyB)Assembly.Load(path).CreateInstance(className); break ; case " C " : // this.strategy = new StrategyC(); className = path + " .StrategyC " ; this .strategy = (StrategyModel.StrategyC)Assembly.Load(path).CreateInstance(className); break ; } } public void ContextInterface() { strategy.AlgorithmInterface(); } }
复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值