Skip to content

Instantly share code, notes, and snippets.

@tomasmalmsten
Created October 31, 2013 11:33
Show Gist options
  • Save tomasmalmsten/7248215 to your computer and use it in GitHub Desktop.
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
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