Monday 20 June 2011

Template method and Command pattern, a good combination to create generic algorithms


Introduction
With this post I want to share some strategies to face generic algorithms where each step is no tight with concepts. Just on the fly configuration (i.e. using IoC framework) is tight with a specific use case.
   
Definition of patterns 
Template method pattern defines the program skeleton of an algorithm. One or more of the algorithm steps can be overridden by subclasses to allow differing behaviours while ensuring that the overarching algorithm is still followed.


Command pattern defines an object used to represent and encapsulate all the information needed to call a method at a later time. This information includes the method name, the object that owns the method and values for the method parameters.
Three terms with the command pattern are:
The client instantiates the command object and provides the information required to call the method at a later time.
The invoker decides when the method should be called.
The receiver is an instance of the class that contains the method's code.


New Template method approach
Both patterns used together can help to construct a generic algorithm that conceptually executes generic steps.
From template, the idea of creating an algorithm that executes several steps to achieve a task.
From the command, The idea of building general components that need to delegate, sequence or execute method calls at a time of their choosing without the need to know the owner of the method or the method parameters.




With use of an IoC framework, the instance variable List steps can be injected with specific implementations.
The next two sequence diagrams show the interactions between all the components.
In the first, the template is injected with the following instances of

  • ConcreteCommand2
  • ConcreteCommand4 
  • ConcreteCommand5 



In the second, the template is injected with the following instances of
  • ConcreteCommand1
  • ConcreteCommand3 
  • ConcreteCommand5   


No comments:

Post a Comment