.NET 下运用策略模式
<div id="cnblogs_post_body">我简单的理解策略模式就是把行为(方法)单独的抽象出来,并采用组合(Has-a)的方式,来组合行为和实体的一种模式。再来个官方的解释:Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
网上也有很多资源介绍这个模式,我也不从头说起了。在.NET中委托给我们给我们提供了简单实现策略模式的方法,可以简单的把一个委托看成是一种策略方法,而且还能借组lmabda表达式这样的形式来表达出来。比如,.NET中对数组排序的Sort的方法就是一个策略模式的实现模板。
<div class="cnblogs_code">static void Main(string[] args){ int[] array = new int[] { 3, 2, 8, 1, 5 }; //相当于是重新设置了一个排序策略 Array.Sort(array, (a, b) => b - a); //这里也相当于为每个元素安排了一个输出策略 Array.ForEach(array, Console.WriteLine);}
页:
[1]