使用策略模式+工厂模式优化if-else分支判断

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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值