您的位置:首页 > 其它

设计模式笔记之 -Template Method & Strategy

2005-09-12 18:10 459 查看

Template Method:

通过抽象分离有共性的方法放入基类中,从而完成通用算法,将所有实现都交给该基类的抽象方法。

运用此模式主要在于建立抽象基类,制定抽象方法。



注意:不要滥用模式,如果把一个简单的问题复杂话了,那还不如不用模式,把一个简单的方法放在抽象基类里,并不能带来什么好处,反而增加了代码的复杂性。

冒泡排序的例子:

1 public abstract class BubbleSorter
5
31
32 public class IntBubbleSorter : BubbleSorter
36 public class BubbleSorter
5 public interface ISortHandle
5 public class IntSortHandle : ISortHandle
5 [TestFixture]
5 public class BubbleSorter_Test
6 {
7 public BubbleSorter_Test()
8 {
9 }
10
11 [Test]
12 public void Test_IntSort()
13 {
14 int[] invalue = new int[]{3,5,2,7,8,1,9};
15 int[] result1 = new int[]{1,2,3,5,7,8,9};
16 int[] result2 = new int[]{9,8,7,5,3,2,1};
17
18 IntSortHandle ish = new IntSortHandle(invalue);
19 BubbleSorter bs = new BubbleSorter(ish);
20
21 Console.WriteLine("交换的次数:" + bs.Sort(true));
22 Assert.AreEqual(result1,ish.GetArray());
23
24 Console.WriteLine("交换的次数2:" + bs.Sort(invalue,false));
25 Assert.AreEqual(result2,ish.GetArray());
26 }
27 }

在这里需要排序的类对排序实现类一无所知,它只知道自己继承自接口,需要关系的只是实现接口方法即可,这样就大大提高了类的实用性,如果在自定义类中需要实现排序功能,那么它只需要继承相应的接口即可,这没有与高层算法的依赖。

结论:

Template Method和Strategy模式都可以用来分离高层算法和低层的具体实现细节,都允许高层算法独立于它的具体实现而重用,此外Strategy还提供了具体实现细节独立于高层算法的重用,不过为此付出的代价就是代码的复杂性提高了,增加了运行开销。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: