Practical Usages of Design Patterns – The Template Method and The Strategy

Introduction

This is just an easy to learn example for who that is going to apply design patterns within his codes. Here you find a comparison of the Template Method and the Strategy design patterns implementation.

The Template Method Design Pattern

Sometimes we need to define a basic top level protocol which contains common behaviors of a phenomena in the way each instance can response differently. Assume we define a class for animals. We know we have to an abstract class for animals. Because animal is a very wide category. Also animal doesn’t have any instance. I mean we have instances of dogs or cats which both are animal. However we cant find any exactly animal instance. We always define these kind of overal classes as abstract which aren’t able to be instantiated directly.

Then Animal class has at least move() method. However each race of animals responses tho the move() differently. For example a snake moves by creeping. Dog moves by running. So we have a common class for animals which needs to perform different responses for the same move() method.

Now I want to use a more sensible example. Assume an office automation application which is responsible for official or personal communications. As we know there are some different ways to notify other people. For example you can send them email, or send SMS, or tweet or even you may write on your wall or people’s wall in facebook to let to notify people.
For all those actions you first need to login. Then you need to write content, and felinely you need to logout.

Template method design pattern is a charm template to do this.  At first I defined the GlobalNotifer which covers all notifier systems as the following abstract class:

package com.hexican.notifier;

public abstract class GlobalNotifier {

    public abstract boolean login(String user, String password);

    public abstract void putMessage(String message);

    public abstract void logout();

    //work as template method
    public void doNotify(String user, String password, String message) {
        if (login(user, password)) {
            putMessage(message);
            logout();
        } else {
            System.out.println("Wrong user or password!");
        }
    }
}

Then I defined two notifiers for Yahoo and Facebook. They both extend GlobalNotifier.

YahooNotifier is responsible for connecting to Yahoo mail and sending emails to a pre-defined user list. Also YahooNotifier is loyal to the GlobalNotifier protocol:

package com.hexican.notifier;

public class YahooNotifier extends GlobalNotifier {
    public boolean login(String user, String password) {
        // Knows how to login to Yahoo.
        return false; //
    }

    public void putMessage(String message) {
        // Knows how to call send the message to Yahoo.
    }

    public void logout() {
        // Knows how to logout from Yahoo.
    }
}

Also I need a Facebook notifier, So I do the same things that I did in YahooNotifier:

package com.hexican.notifier;

public class FacebookNotifier extends GlobalNotifier {
    public boolean login(String user, String password) {
        // Knows how to login to facebook.
        return false; //
    }

    public void putMessage(String message) {
        // Knows how to call send the message to facebook.
    }

    public void logout() {
        // Knows how to logout from facebook.
    }
}

I developed a simple test class to call both Yahoo and Facebook notifiers together:

package com.hexican.notifier;

public class TestNotifiers {
    public static void main(String[] args) {
        YahooNotifier yahoo = new YahooNotifier();
        yahoo.doNotify("amir", "pass1", "Does anybody here remember Vera Lynn?");

        FacebookNotifier facebook = new FacebookNotifier();
        facebook.doNotify("amir", "pass2", "Does anybody else in here, feel the way I do?");
    }
}

Usage

  • It is better to use the Template Method design pattern to capture an algorithm in an abstract superclass, but defer the implementation of individual steps to subclasses.
  • The Template Method design pattern gives a common interface for such a different instances. So It can be used for keeping instances align with the business policy and conventions.


  • The Strategy Design Pattern

    Now, I am going to re-implement above sample using The Strategy Pattern instead of The Template Method. Actually The Strategy Pattern is an alternative to The Template Method pattern. The Strategy Pattern factors the variant behavior into an interface.

    The first step is to move the template method into an interface, which will look like this:

    package com.hexican.notifier;
    
    public interface MyNotifer {
        void doNotify(String user, String password, String message);
    }

    The Yahoo and the facebook Implementations of this interface don’t need to subclass any particular class so I have the maximum possible freedom:

    package com.hexican.notifier;
    
    public class YahooNotifier implements MyNotifer {
        public void doNotify(String user, String password, String message) {
            if (login(user, password)) {
                putMessage(message);
                logout();
            } else {
                System.out.println("Wrong user or password!");
            }
        }
        private boolean login(String user, String password) {
            // Knows how to login to Yahoo.
            return false; //
        }
    
        private void putMessage(String message) {
            // Knows how to call send the message to Yahoo.
        }
    
        private void logout() {
            // Knows how to logout from Yahoo.
        }
    }

    And

    package com.hexican.notifier;
    
    public class FacebookNotifier implements MyNotifer {
        public void doNotify(String user, String password, String message) {
            if (login(user, password)) {
                putMessage(message);
                logout();
            } else {
                System.out.println("Wrong user or password!");
            }
        }
        private boolean login(String user, String password) {
            // Knows how to login to Facebook.
            return false; //
        }
    
        private void putMessage(String message) {
            // Knows how to call send the message to Facebook.
        }
    
        private void logout() {
            // Knows how to logout from Facebook.
        }
    }

    Now I can write a concrete Context class that depends on an instance variable of MyNotifier interface. I must also provide a means of setting this helper, either in the constructor or through a bean property:

    package com.hexican.notifier;
    
    public class Context {
    
        private MyNotifer myNotifer;
    
        // Constructor
        public Context(MyNotifer myNotifer) {
            this.myNotifer = myNotifer;
        }
    
        public void doNotify(String user, String password, String message) {
            myNotifer.doNotify(user, password, message);
        }
    }

    For calling different notifiers we just need to pass different notifiers to the context constructor:

    package com.hexican.notifier;
    
    public class TestNotifiers {
        public static void main(String[] args) {
            Context context;
    
            context = new Context(new YahooNotifier());
            context.doNotify("amir", "password1", "Does anybody here remember Vera Lynn?");
    
            context = new Context(new FacebookNotifier());
            context.doNotify("amir", "password2", "Does anybody else in here, feel the way I do?");
    
        }
    
    }

    Usage

  • When all steps vary.
  • When the class that implements the steps needs an independent inheritance hierarchy.
  • Wen object behavior needs to be changed in runtime.
  • This entry was posted in Java, Software Engineering. Bookmark the permalink.

    5 Responses to Practical Usages of Design Patterns – The Template Method and The Strategy

    1. angel says:

      ur description is wonderfully easy to understand these patterns.
      i’m so appreciate it.i really enjoyed reading ur article.
      angel from iran!

    2. angel says:

      u know i wished u had broke down other patterns in ur blog too.

    3. Siddhartha Roy says:

      Excellent Article. Very well explained.

    4. Hardik says:

      very helpful article to understand both the patterns from scratch! Thanks!

    Leave a Reply