java - 策略模式和模板模式该怎么区分?
伊谢尔伦
伊谢尔伦 2017-04-17 14:33:26
0
2
502

看了这两个设计模式之后, 对于简单直接的例子可以判断, 策略模式就是定义算法族, 然后通过组合算法族和委托的办法来实现类, 模板方法则是父类定义算法的骨架,子类再来实现骨架中的部分步骤;

但是有两个例子我很不理解:
1. thingking in java里面有讲到File.list(FilenameFilter filter)FilenameFilter就是策略设计模式. 这是书中的原文:

因为list()实现了基本的功能, 而且按照FilenameFilter的形式提供了这个策略, 以便完善list()在提供服务时所需的算法

我觉着 list()在内部使用FilenameFilter, 也可以理解为File定义好了算法骨架, 由FilenameFilter补齐部分步骤, 这么想 这就是 模板方法; Arras.sort()

  1. head first设计模式 里面讲到Arrays.sort(Object[] objects)和``Comparable"是模板方法设计模式. 这是head first的原文:

因为这个模式的重点在于提供一个算法, 并让子类实现某些步骤而数组的排序做法明显也是如此.

我是这么想的: sort()函数提供了基本的功能, 元素的比较由comparable算法族来实现; 我这样想, sort()函数就是策略模式;

到底这两者该怎么区分呢? 还是我的理解哪里有问题?

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(2)
迷茫
  • Strategy, object behavior pattern =》Use combination method
  • Template method, behavioral class pattern => Use inheritance

There are instructions in the Q&A in Head First

Because the Strategy pattern uses object composition. In a way, you're right - we use array objects to sort our arrays, and this part is very similar to the Strategy pattern. But remember that in the Strategy pattern, the classes you compose implement the entire algorithm. The sorting algorithm implemented by the array is not complete, it requires a class to fill in the implementation of the compareTo() method. So we think this is more of a template approach.

There is another API in the Arrays class:

public static <T> void sort(T[] a,
            Comparator<? super T> c)

If you look at Comparator as an algorithm, it feels like this API is more like a strategy model.


To put it bluntly, the object of the template method pattern only implements a certain step of the algorithm, and most of the specific algorithms are defined in the parent class. The object of the Strategy pattern implements the entire algorithm.

Ty80

Design patterns are just the result of abstraction. The main function of abstraction is to increase the readability, reusability and scalability of the code. So you don’t have to worry about whether you are using a template or a strategy.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template