Strategy Pattern using Lambdaj Switcher

As an extension to one of my earlier posts on strategy pattern, here i am providing a sample implementation using Lambdaj Switcher.

StrategyPatternSwitcherExample.java


package com.idodevjobs.example;

import ch.lambdaj.function.closure.Switcher;

public class StrategyPatternSwitcherExample {

    private Gender gender;
    private String message;
    private Switcher<GenerateGreetingStrategy> generateGreetingStrategySwitcher;

    public StrategyPatternSwitcherExample (Gender gender, String message) {
        this.gender = gender;
        this.message = message;

        generateGreetingStrategySwitcher = new Switcher<>();
        generateGreetingStrategySwitcher.addCase(Gender.MALE, new GenerateGreetingForMen());
        generateGreetingStrategySwitcher.addCase(Gender.FEMALE, new GenerateGreetingForWomen());
        generateGreetingStrategySwitcher.setDefault(new GenerateGreetingForWomen());
    }

    public static void main(String args[]) {
        StrategyPatternSwitcherExample strategyPatternSwitcherExample1 = new StrategyPatternSwitcherExample(Gender.MALE, "Jack, Good morning !!");
        StrategyPatternSwitcherExample strategyPatternSwitcherExample2 = new StrategyPatternSwitcherExample(Gender.FEMALE, "Laura, Good afternoon !!");
        System.out.println(strategyPatternSwitcherExample1.generateGreeting());
        System.out.println(strategyPatternSwitcherExample2.generateGreeting());
    }

    private String generateGreeting() {
        return generateGreetingStrategySwitcher.exec(gender).generateGreeting(message);
    }
}

enum Gender {
    MALE, FEMALE
}

Refer to my earlier post for source code of other required classes such as GenerateGreetingStrategy.java, GenerateGreetingForMen.java and GenerateGreetingForWomen.java.

This also serves as an example for Lambdaj Switcher. Lambdaj Switcher is an excellent alternative to java’s switch-case.

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

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s