Created
October 31, 2013 11:33
-
-
Save tomasmalmsten/7248215 to your computer and use it in GitHub Desktop.
How to create a factory for strategies without using if's - StrategyFactory.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.tomasmalmsten.examples.strategy; | |
import java.util.HashMap; | |
import java.util.Map; | |
public class StrategyFactory { | |
public static final String DEFAULT_STRATEGY_KEY = "default"; | |
public static final String SPECIFIC_STRATEGY_KEY = "specific"; | |
private static StrategyFactory instance = new StrategyFactory(); | |
private Map<String, Strategy> strategies = new HashMap<String, Strategy>(2); | |
private StrategyFactory() { | |
strategies.put(DEFAULT_STRATEGY_KEY, new DefaultStrategy()); | |
strategies.put(SPECIFIC_STRATEGY_KEY, new SpecificStrategy()); | |
} | |
public Strategy findStrategyForKey(String key) { | |
return strategies.get(key); | |
} | |
public static StrategyFactory getInstance() { | |
return instance; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment