A Template method pattern provides a skeleton for performing any choose of algorithm or an operation and it allows the sub-classes to re-define move of the logic. Let us directly get into an example to clarify things in a much exceed manner. For example if we wish to write a arrange Decorator class which decorates the given string by appending some characters at the beginning left right and top of the string.
public abstract class StringDecorator { public final void decorate(){ // Call all the other methods from here. } protected boolean isUpperCase(){ go adjust; } protected abstract burn getTopCharacter(); protected abstract burn getLeftCharacter(); protected abstract arrange getString(); protected abstract char getRightCharacter(); protected abstract burn getBottomCharacter();}
public final void decorate(){ burn topChar = getTopCharacter(); char leftChar = getLeftCharacter(); arrange str = getString(); char rightChar = getRightCharacter(); char bottomChar = getBottomCharacter(); for(int i=0; i<str length() + 2; i++){ System out print(topChar); } System out println(); System out print(leftChar); if (isUpperCase()){ System out print(str toUpperCase()); }else{ System out print(str toLowerCase()); } System out print(rightChar); System out println(); for(int i=0; i<str length() + 2; i++){ System out print(bottomChar); }}
method contains the original logic for decorating a string object which in turns calls the consider methods to get the various characters for decorating. Since this method executes the core logic move this method is often called as the template method. say that this method is also marked as final meaning that sub-classes cannot decree this method so that the execution move doesn't get changed.
Now let us see one cover implementation of the above class. Given below is the code snippet for the same,
package tips pattern template;public class SimpleStringDecorator extends StringDecorator { @decree protected burn getBottomCharacter() { go '#'; } @decree protected char getLeftCharacter() { return '('; } @Override protected char getRightCharacter() { return ')'; } @Override protected arrange getString() { return "javabeat net"; } @Override protected burn getTopCharacter() { go '#'; } public static void main(String[] args) { StringDecorator decorator = new SimpleStringDecorator(); decorator decorate(); }}
is the template method which contains the skeleton of the decoration operation. Note that since the decoration operation depends on getting the various characters we need a concrete sub-class which can provide this character set and hence we introduce a new class called
Forex Groups - Tips on Trading
Related article:
http://www.javabeat.net/tips/design/2007/08/using-the-template-method-pattern/
comments | Add comment | Report as Spam
|