消除if-else,简单工厂+策略模式

 这是一个简单的if-else

public void operationByWorkItemType(String studentType){
        if("bks".equals(workItemType)){
            doBksOperation();
        }else if("sss".equals(workItemType)){
            doSssOperation();
        }else if("bss".equals(workItemType)){
            doBssOperation();
        }
    、、、、、、
    }

定义一个接口

public interface StudentTypeOperation {
    /**
     * 根据studentType不同,对应操作不同
     */
    void operate();
}

有几个判断定义几个类

@Component
@AllArgsConstructor
public class BksStrategy implements StudentTypeOperation {
    @Override
    public void operate() {
        doBksOperation();
    }
}
@Component
@AllArgsConstructor
public class SssStrategy implements StudentTypeOperation {
    @Override
    public void operate() {
        doSssOperation();
    }
}
@Component
@AllArgsConstructor
public class BssStrategy implements StudentTypeOperation {
    @Override
    public void operate() {
        doBssOperation();
    }
}

将这些spring管理的实例注入静态map

SpringUtil是hutool工具类的

public class StudentTypeFactory {
    private static final Map<String,StudentTypeOperation> STUDENT_ITEM_TYPE_MAP =new HashMap<>();
    static {
        STUDENT_ITEM_TYPE_MAP.put("sss", SpringUtil.getBean(PasswordTokenGranter.class));
        STUDENT_ITEM_TYPE_MAP.put("sssss", SpringUtil.getBean(CaptchaTokenGranter.class));
        STUDENT_ITEM_TYPE_MAP.put("three", SpringUtil.getBean(RefreshTokenGranter.class));
        STUDENT_ITEM_TYPE_MAP.put("fore", SpringUtil.getBean(SocialTokenGranter.class));
    }
    public static void operate(String studentType){
        STUDENT_ITEM_TYPE_MAP.get(studentType).operate();
    }
}

调用

public void operationByStudentType(String studentType){
        StudentTypeFactory.operate(studentType);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值