Design Patterns: Strategy Pattern

This blog post gives an example implementation of Strategy Pattern.

public interface GenerateGreetingStrategy {
    public String generateGreeting(String message); 

public class GenerateGreetingForMen implements GenerateGreetingStrategy {
    public String generateGreeting(String message) {
        return "Mr."+message;

public class GenerateGreetingForWomen implements GenerateGreetingStrategy {
    public String generateGreeting(String message) {
        return "Ms."+message;

import java.util.HashMap;
import java.util.Map;

public class StrategyPatternExample {
    private Map<String, GenerateGreetingStrategy> strategyMap;
    private String gender;
    private String message;
    public StrategyPatternExample()  {
        strategyMap = new HashMap<>();
        strategyMap.put("Men", new GenerateGreetingForMen());
        strategyMap.put("Women", new GenerateGreetingForWomen());
    public StrategyPatternExample(String gender, String message) {
        this.gender = gender;
        this.message = message;
    public static void main(String[] args) {
        StrategyPatternExample strategyPatternExample1 = new StrategyPatternExample("Men", "Jack, Good morning !!");
        StrategyPatternExample strategyPatternExample2 = new StrategyPatternExample("Women", "Laura, Good afternoon !!");
    private String generateGreetingUsingSwitchCase() {
        switch (gender) {
            case "Men":
                return "Mr."+message;
            case "Women":
                return "Ms."+message;
                return message;
    private String generateGreetingUsingStrategy() {
        return strategyMap.get(gender).generateGreeting(message);

It’s always advisable to use design patterns wherever possible and applicable.
Design Patterns are proven solutions to the most common problems a programmer encounter.
Strategy Pattern can be used in instances where we need to handle requests in different ways according to the data.
This example uses strategy pattern vs switch case.

a) Handling message of types such as text, json, xml etc.,
b) Compress files of different types such as zip, rar etc.,
c) Parse text using different regex based on input or a flag.,

Please comment below with questions and/or feedback.

This entry was posted in java and tagged , , , . Bookmark the permalink.

One Response to Design Patterns: Strategy Pattern

  1. Pingback: Strategy Pattern using Google Lambdaj Switcher | iDoDevJobs

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s