/java/

Command pattern

2014-09-18 22:22:11

Main.java

package command;

import command.meal.FishWithVegetables;
import command.meal.MealMenu;
import command.meal.Pizza;
import command.meal.PorkChopWithPotatoes;

public class Main {

    public static void main(String[] args) {

        MealMenu menu = new MealMenu();

        menu.register(new Pizza());
        menu.register(new FishWithVegetables());
        menu.register(new PorkChopWithPotatoes());

        menu.getMeal("Fish With Vegetables").execute();
    }
}

MealCommand.java

package command.meal;

public interface MealCommand {

    void execute();

    String getName();
}

NoSuchMeal.java

package command.meal;

public class NoSuchMeal implements MealCommand {

    @Override
    public void execute() {
        System.out.println("We just prepared for you: " + getName());
    }

    @Override
    public String getName() {
        return "No Such Meal";
    }
}

Pizza.java

package command.meal;

public class Pizza implements MealCommand {

    @Override
    public void execute() {
        System.out.println("We just prepared for you: " + getName());
    }

    @Override
    public String getName() {
        return "Pizza";
    }
}

PorkChopWithPotatoes.java

package command.meal;

public class PorkChopWithPotatoes implements MealCommand {

    @Override
    public void execute() {
        System.out.println("We just prepared for you: " + getName());
    }

    @Override
    public String getName() {
        return "Pork Chop With Potatoes";
    }
}

FishWithVegetables.java

package command.meal;

public class FishWithVegetables implements MealCommand {

    @Override
    public void execute() {
        System.out.println("We just prepared for you: " + getName());
    }

    @Override
    public String getName() {
        return "Fish With Vegetables";
    }
}

MealMenu.java

package command.meal;

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

public class MealMenu {

    private Map

<string, mealcommand=""> meals = new HashMap&lt;&gt;();

    public void register(MealCommand mealCommand) {
        meals.put(mealCommand.getName(), mealCommand);
    }

    public MealCommand getMeal(String name) {

        MealCommand mealCommand = meals.get(name);

        if (mealCommand == null) {
            return new NoSuchMeal();
        }

        return mealCommand;
    }
}