浅谈Java常见设计模式(五)
package com.lgli.behavior.delegatestrategy.v3;
import java.util.HashMap;
import java.util.Map;
/**
*
* 策略工厂
* @author lgli
*/
public class StrategyFactory {
private static final StrategyFactory strategyFactory
= new StrategyFactory();
private static final ControllerStrategy EMPTY_STRATEGY
= new EControllerStrategy();
private StrategyFactory(){}
private static final Map<String,ControllerStrategy> map
= new HashMap<>();
static {
map.put(StrategyKey.A.name(),
new AControllerStrategy());
map.put(StrategyKey.B.name(),
new BControllerStrategy());
map.put(StrategyKey.EMPTY.name(),
new EControllerStrategy());
}
public static StrategyFactory getInstance(){
return strategyFactory;
}
public ControllerStrategy getStrategy(String key){
ControllerStrategy controllerStrategy = map.get(key);
return controllerStrategy == null ?
EMPTY_STRATEGY : controllerStrategy;
}
enum StrategyKey{
A,B,EMPTY
}
}
package com.lgli.behavior.delegatestrategy.v3;
/**
* @author lgli
*/
public class DealController {
private static final DealController dealController
= new DealController();
private DealController(){}
public static DealController getInstance(){
return dealController;
}
public void deal(String key){
StrategyFactory strategyFactory = StrategyFactory
.getInstance();
ControllerStrategy strategy = strategyFactory
.getStrategy(key);
strategy.deal();
}
}
点个赞再走了,谢谢!