Knowing the OO basics does not make you a good OO designer.
策略模式:
策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。
Context(应用场景):
Strategy(抽象策略类):
ConcreteStrategy(具体策略类):
时序图如下
举一个.NET框架里使用Strategy模式的例子,ArrayList类肯定都会用过吧,那么它的Sort方法想必大家也一定不陌生了。Sort方法的定义如下:
public virtual void Sort (IComparer comparer)
可以看到Sort方法接收一个IComparer类型的参数,那么这个IComparer接口是做什么用的呢?下面我们看一段程序,下面的代码示例演示如何使用默认比较器和一个反转排序顺序的自定义比较器,对 ArrayList 中的值进行排序。
using System; using System.Collections; public class SamplesArrayList { public class myReverserClass : IComparer { // Calls CaseInsensitiveComparer.Compare with the parameters reversed. int IComparer.Compare( Object x, Object y ) { return( (new CaseInsensitiveComparer()).Compare( y, x ) ); } } public static void Main() { // Creates and initializes a new ArrayList. ArrayList myAL = new ArrayList(); myAL.Add( "The" ); myAL.Add( "quick" ); myAL.Add( "brown" ); myAL.Add( "fox" ); myAL.Add( "jumps" ); myAL.Add( "over" ); myAL.Add( "the" ); myAL.Add( "lazy" ); myAL.Add( "dog" ); // Displays the values of the ArrayList. Console.WriteLine( "The ArrayList initially contains the following values:" ); PrintIndexAndValues( myAL ); // Sorts the values of the ArrayList using the default comparer. myAL.Sort(); Console.WriteLine( "After sorting with the default comparer:" ); PrintIndexAndValues( myAL ); // Sorts the values of the ArrayList using the reverse case-insensitive comparer. IComparer myComparer = new myReverserClass(); myAL.Sort( myComparer ); Console.WriteLine( "After sorting with the reverse case-insensitive comparer:" ); PrintIndexAndValues( myAL ); } public static void PrintIndexAndValues( IEnumerable myList ) { int i = 0; foreach ( Object obj in myList ) Console.WriteLine( "\t[{0}]:\t{1}", i++, obj ); Console.WriteLine(); } } /* This code produces the following output. The ArrayList initially contains the following values: [0]: The [1]: quick [2]: brown [3]: fox [4]: jumps [5]: over [6]: the [7]: lazy [8]: dog After sorting with the default comparer: [0]: brown [1]: dog [2]: fox [3]: jumps [4]: lazy [5]: over [6]: quick [7]: the [8]: The After sorting with the reverse case-insensitive comparer: [0]: the [1]: The [2]: quick [3]: over [4]: lazy [5]: jumps [6]: fox [7]: dog [8]: brown */
练习:
刘备要到江东娶老婆了,走之前诸葛亮给赵云(伴郎)三个锦囊妙计,说是按天机拆开能解决棘手问题,嘿,还别说,真解决了大问题,搞到最后是周瑜陪了夫人又折兵,那咱们先看看这个场景是什么样子的。
先说说这个场景中的要素:三个妙计,一个锦囊,一个赵云,妙计是亮哥给的,妙计放在锦囊里,俗称就是锦囊妙计嘛,那赵云就是一个干活的人,从锦囊取出妙计,执行,然后获胜。用java程序怎么表现这些呢?
那我们先来看看图?
代码见Patterns.rar