Talk:Template method pattern

From Wikipedia, the free encyclopedia
Jump to: navigation, search
          This article is of interest to the following WikiProjects:
WikiProject Java (Rated Start-class, Low-importance)
WikiProject icon This article is within the scope of WikiProject Java, a collaborative effort to improve the coverage of Java on Wikipedia. If you would like to participate, please visit the project page, where you can join the discussion and see a list of open tasks.
Start-Class article Start  This article has been rated as Start-Class on the project's quality scale.
 Low  This article has been rated as Low-importance on the project's importance scale.
Note icon
This article has been automatically rated by a bot or other tool because one or more other projects use this class. Please ensure the assessment is correct before removing the |auto= parameter.
WikiProject Computer science (Rated Start-class, Low-importance)
WikiProject icon This article is within the scope of WikiProject Computer science, a collaborative effort to improve the coverage of Computer science related articles on Wikipedia. If you would like to participate, please visit the project page, where you can join the discussion and see a list of open tasks.
Start-Class article Start  This article has been rated as Start-Class on the project's quality scale.
 Low  This article has been rated as Low-importance on the project's importance scale.
WikiProject Systems (Rated Start-class, Mid-importance)
WikiProject icon This article is within the scope of WikiProject Systems, which collaborates on articles related to systems and systems science.
Start-Class article Start  This article has been rated as Start-Class on the project's quality scale.
 Mid  This article has been rated as Mid-importance on the project's importance scale.
Taskforce icon
This article is within the field of Operations research.

Example removed[edit]

I removed the following example and replaced it with mine, which I translated from the french version. Feel free to revert if you have reasons to do so. If not, feel free to correct my english :)

<removed stuff>

For example, given a skeleton for common operations on data structures, there may be a few common operations and some specific to the data structure. The data structure template class can provide a template for each newly added data structure class.

class CDatastructure_Template  
   //Common operations: Algorithm Template
   void  virtual CleanAll()=0;
   void  virtual AddNode(Node *node)=0;
   void  virtual DeleteNode(Node *node)=0;
   long  virtual GetNumElements()=0;   
   Node* virtual GetTopNode()=0;
   Node* virtual GetNextNode(Node *CurrentNode)=0;

class CLinkList_ConcTemplate:public Datastructure_Template; 
class CQueue_ConcTemplate:public Datastructure_Template;  
class CArray_ConcTemplate:public Datastructure_Template; 
class CTree_ConcTemplate:public Datastructure_Template;        

New data structure class can be derived from the CLinkList_ConcTemplate, with operations modified as necessary.

</removed stuff>

Peer pattern[edit]

The Peer pattern seeks to solve the same or similar problems as the Template method pattern but uses Object composition instead of Polymorphism (computer science). In fact, you might just call it plain old composition.

Allow me to modify the template method of our example:

 /* A template method : */
 final void playOneGame(int playersCount){
   this.playersCount = playersCount;
   int j = 0;
   while( ! endOfGame() ){
     makePlay( j );
     j = (j + 1) % playersCount;

Now consider that makePlay, updateDisplay, and printWinner are somewhat orthogonal to each other. I could have P different play styles (aggressive, defensive, etc.), display to D different devices (gui, command line, web-browser, etc.), and print the winner in W different ways (on screen, by email, etc.). Instead of creating the potential P x D x W subclasses of Chess or Monopoly Game, refactor to use peers.

Expanding from the Chess example:

class MyChess extends Chess{

 // these are the peers of MyChess.
 private Player players[];
 private Display display;
 private WinnerNotifier wn;

 public MyChess(Player[] players, Display display, WinnerNotifier notifier){
   this.players = players;
   this.display = display;
   this.notifier = notifier;

 void makePlay(int player){

 void printWinner(){

 void updateDisplay(){

Now, supposing that I have elsewhere implemented polymorphic subclasses of Player, Display, and WinnerNotifier, I can compose arbitrary mixtures of MyChess. For example:

Player players[] = new Player[2];
players[0] = new AggressiveChessPlayer();
players[1] = new DefensiveChessPlayer();
Chess myChess = new MyChess(players, new CommandLineChessDisplay(), new EmailChessWinnerNotifier());

Besides the combinatorial benefits, peers provide better testability. Here's why:

  1. Peers are more focused in purpose; eg. the Player peer handles decision making and that's all.
  2. Peers exist independently of their template class. We can instantiate and execute peers outside of their template methods.

Though I have turned a blind eye to it in my example, the peers mentioned above may need to have intimate knowledge of the game state. The peers may thus become highly coupled to their parent peer (MyChess in my example). In this case, the Template method pattern might make more sense. 22:06, 22 March 2006 (UTC)

C++ example removed[edit]

I just removed the C++ example (BubbleSort and friends) from the article; I don't think it provided any clarifying information that the Java example didn't, and the Java example is much clearer — lacking as it does most of C++'s fiddling with virtual and so on, which is irrelevant to the pattern described in this article. (Also, the C++ example felt very contrived; nobody uses inheritance to subclass a hand-coded BubbleSort when qsort() is provided by the standard library! :)

Those editors who are interested in providing good code examples for this and other articles, please see Wikipedia talk:WikiProject Programming languages#Category:Articles with example code proposal and call for volunteers, where I'm trying to get some people interested in picking a few standard languages in which to do code examples, so we don't end up with quite so many "language soup" articles — as I see most of the "Design Patterns" articles have become! --Quuxplusone 09:38, 2 December 2006 (UTC)

What's with the C++ example that's in here now? (21st of November 2008) That lengthy piece of code demonstrates template class specialization using a traits class. It does not demonstrate the template method pattern, it merely overloads a method (clone()) in a template class. It has a lot of redundancy, is basically besides any point, and it certainly has nothing to do with this article. I'd like to see this replaced with a true example of using C++ templates to implement this pattern. —Preceding unsigned comment added by (talk) 10:47, 21 November 2008 (UTC)


Does the phrase "the abstract method is the smallest unit of granularity" have a meaning in this context?

Some or all of the abstract methods can be specialized in the subclass, the abstract method is the smallest unit of granularity, allowing the writer of the subclass to provide particular behavior with minimal modifications to the larger semantics

C++ example too complex?[edit]

I think the example for C++ is too complex. Why not use the game example also used for the other language? The C++ one uses clone and whatnot, which is not subject of this article. I will write a better example if i got some time (which implements the game example with templates in C++). Also, a majority of the C++ Standard library *uses* the virtual dispatch to implement template method. Just look at ctype<> which has a bunch of virtual do... functions. And the stream buffer functions pub.. functions that call virtual functions in the end.

Update: I replaced the C++ example to do the same as the java one and added some explanation of what the drawbacks are. —Preceding unsigned comment added by (talk) 10:51, 29 December 2008 (UTC)

Relevance to MVC?[edit]

I don't think most of the first paragraph of the Introduction is accurate. In particular the overridden functions in a Template Method have nothing to do with 'views' in the MVC sense, which is literally about presenting a view of the data, whereas Template Methods are typically about algorithms and operations. If changing an implementation in a derived class constitutes being a View, then pretty much everything in the GoF book is a variant or subset of MVC. And that's not what MVC represents. To quote from the MVC page, it "isolates business logic from user interface considerations". The Template Method (as well as pretty much every GoF pattern) can be used for this in some way, but that is just 1 of many applications.

Along similar lines, I don't see how XSLT templates are relevant here. This seems to be extending the definition of a template method to massively broad and vague proportions. Should we call different web browsers an implementation of the template method, for the same reason? I think not. Kylotan (talk) 15:21, 2 July 2009 (UTC)

Thought the same thing myself. The first paragraph should go! -- (talk) 23:58, 3 February 2010 (UTC)

Make the Java example compile?[edit]

I've expanded the (very nice!) Java example by some lines such that it compiles without errors and outputs some game specific lines when called as java PlayAGame Chess or java PlayAGame Monopoly from the command line. It has now 106 lines instead of 84. Anyone interested in replacing the original example by the expanded one? (talk) 13:54, 12 August 2009 (UTC)

ad: section usage[edit]

imho there is a mistake: nothing can ever be called from an abstract class, as abstract classes can never be instantiated. hence the part about hollywood principle... is plain wrong. suggestions? Kind regard - skrio (Skrio (talk) 06:23, 25 April 2010 (UTC)).

I don't see the problem. While an abstract class can't be instantiated, a subclass can, so playOneGame(int) can be called on a Monopoly instance or a Chess instance. Or am I not understanding your question? —Ben FrantzDale (talk) 12:25, 26 April 2010 (UTC)
BenFrantzDale, please excuse the late answer. You are right, thank you for clarification.--Skrio (talk) 12:24, 9 December 2010 (UTC)

Hook method[edit]

The article doesn't define properly the importance of the template method for extensibility of code. Though the article mentions the hook method, it doesn't describe or shows its use for extend behavior in subclasses. In a template method the hook method is placed usually at the end of the algorithm. The default behavior for this method is do nothing. The subclasses extends the behavior of the template overriding the default action. --Klodr (talk) 21:21, 30 December 2012 (UTC)

Initial description[edit]

The first sentence: "In software engineering, the template method pattern is a behavioral design pattern that defines the program skeleton of an algorithm in a method, called template method, which defers some steps to subclasses." must be credited to the canonical "Design Patterns", E. Gamma et al. It's almost a crime that the article doesn't include this book in the references. --Klodr (talk) 21:27, 30 December 2012 (UTC)