1.定义策略接口
public interface Strategy {
/**
* 根据不同的垃圾处理不同的收运逻辑
* @param type
* @return
*/
public String collectGarbage(Integer type);
}
2.针对不同的逻辑处理实现不同的业务
/**
* 有害垃圾收运策略
*/
public class HarmfulGarbageStrategy implements Strategy{
@Override
public String collectGarbage(Integer type) {
return null;
}
}
/**
* 厨余垃圾收运策略
*/
public class KitchenGarbageStrategy implements Strategy {
@Override
public String collectGarbage(Integer type) {
return null;
}
}
3.定义策略工厂根据传递的类型创建不同的策略
/**
* 策略工厂
*/
public class StrategyFactory {
private static final Map<String, Strategy> strategies=new HashMap<>();
static {
//有害垃圾收运策略
strategies.put("Harmful",new HarmfulGarbageStrategy());
//厨余垃圾收运策略
strategies.put("Kitchen",new KitchenGarbageStrategy());
}
public static Strategy getStrategy(String type){
if(type == null || type.isEmpty()){
throw new IllegalArgumentException("type should not be empty.");
}
return strategies.get(type);
}
}