本文介绍了为什么JdbcTemplate是Template方法设计模式的示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我的注意力被 。但是,为什么这是一个模板方法,而不仅仅是一个巧妙的编码技巧。在我看来,它似乎没有任何模板方法具有的特征。

解决方案

我同意- JdbcTemplate 不是 template method 设计模式的示例。使用的设计模式是。



请注意,两种模式的目标和效果非常相似,主要区别在于 template方法使用继承而 callback 使用合成(某种)-请参见为什么可能会更喜欢。


I was reading about design patterns, in particular about the template method, when my attention was caught by this question on SO.

After reading the explanation and specific code I am still wondering why this is an example of the 'Template method' design pattern.

According to GoF, the intent of this pattern is:

and has two participants:


Why is the code in 'JdbcOperations' considered to be an 'Template method' design pattern?

  • I dont see any 'global/general' algorithm being defined in the super/abstract class, even when I compare it with the code in a similar file like 'JmsTemplate'.
  • None of the functions implemented in the concrete classes are also defined in the super class. All the defined methods are added through the use of the interfaces, in this case the interface 'JdbcOperations', and none actually override the ones in the parent.

I get the fact that it is extremely handy for eliminating boilerplate code. But why is this a template method and not just a nifty coding trick. To me it looks like it shares none of the characteristics that a template method has.

解决方案

I concur - JdbcTemplate isn't an example of template method design pattern. The design pattern used is callback.

Note that the goal and effect of both patterns is very similar, the main difference is that template method uses inheritance while callback uses composition (sort of) - see https://en.wikipedia.org/wiki/Composition_over_inheritance for why this might be preferred.

这篇关于为什么JdbcTemplate是Template方法设计模式的示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 18:16