if语句优化 策略模式

先看一下需求场景,在对接企微通讯录回调通知api的时候,它下面有新增成员通知,删除成员通知,更新成员通知等情况,通知主要由ChangeType来区分,我们要通过这个ChangeType的类型处理不同的业务逻辑。

如果用简单粗暴的方法来实现的话就是这个样子:

        String changeType = "create_user";
        if (changeType.equals("create_user")){
            //创建成员逻辑
            
        }else if(changeType.equals("update_user")){
            //更新成员逻辑
            
        }else if (changeType.equals("del_external_contact")){
            //删除成员逻辑
            
        }else ....

这样的写法缺点就是过多的if else 导致阅读不方便,逻辑过于复杂,代码多长,也不利于后期的维护工作。
那应该怎样重构呢?
if else过多的话,一般都是用策略模式来进行重构,策略模式也非常的简单。先定义一个接口,各种处理分支实现这个接口,定义好 条件->处理类的映射关系,然后根据条件找到响应的处理类执行即可,当有新的分支的话,只需要增加一个接口实现类,增加一个条件->映射类的映射关系即可。还是很好容易理解的。
实现思路如下:

  1. 先定义一个ICropReceiveEventService接口,里面给个handleEvent方法,处理不同的业务逻辑。
  2. 根据具体的业务逻辑(insert/update/delete),实现ICropReceiveEventService接口,然后将这些实现类都注册到Spring Bean容器中。
  3. 在我们接收事件回调接口里面调用方法,获取到ICropReceiveEventService实例。
  4. 调用ICropReceiveEventService接口的handleEvent方法,从而执行相应逻辑。
    具体实现代码如下:
    ICropReceiveEventService接口:
package com.boot.handleEvent.service;

import com.boot.handleEvent.entity.WxCropEventXml;

public interface ICropReceiveEventService {

    /**
     * 事件处理
     * @param wxCropEventXml
     */
    void handleEvent(WxCropEventXml wxCropEventXml);

}

创建成员事件实现类:

package com.boot.handleEvent.service.impl;

import com.boot.handleEvent.Factory.CropReceiveFactory;
import com.boot.handleEvent.entity.WxCropEventXml;
import com.boot.handleEvent.enums.CropReceiveEvent;
import com.boot.handleEvent.service.ICropReceiveEventService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

/**
 * @Author: laz
 * @CreateTime: 2022-09-22  15:11
 * @Version: 1.0
 */
@Service("addUserContactServiceImpl")
@Slf4j
public class AddUserContactServiceImpl implements ICropReceiveEventService {


    /**
     * 类一加载 将当前对象转入map
     * @param addUserContactServiceImpl
     */
    @Autowired
    @Qualifier("addUserContactServiceImpl")
    private void register(ICropReceiveEventService addUserContactServiceImpl) {
        CropReceiveFactory.set(CropReceiveEvent.CREATE_USER.value(), addUserContactServiceImpl);
    }

    @Override
    public void handleEvent(WxCropEventXml wxCropEventXml) {
        log.info("创建成员事件操作逻辑");
    }
}

更新成员事件实现类:

package com.boot.handleEvent.service.impl;

import com.boot.handleEvent.Factory.CropReceiveFactory;
import com.boot.handleEvent.entity.WxCropEventXml;
import com.boot.handleEvent.enums.CropReceiveEvent;
import com.boot.handleEvent.service.ICropReceiveEventService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

/**
 * @Author: laz
 * @CreateTime: 2022-09-22  15:13
 * @Version: 1.0
 */
@Service("editUserContactServiceImpl")
@Slf4j
public class EditUserContactServiceImpl implements ICropReceiveEventService {



    /**
     * 类一加载 将当前对象转入map
     * @param editUserContactServiceImpl
     */
    @Autowired
    @Qualifier("editUserContactServiceImpl")
    private void register(ICropReceiveEventService editUserContactServiceImpl) {
        CropReceiveFactory.set(CropReceiveEvent.UPDATE_USER.value(),editUserContactServiceImpl);
    }

    @Override
    public void handleEvent(WxCropEventXml wxCropEventXml) {
        log.info("编辑成员事件操作逻辑");
    }
}

删除客户事件实现类:

package com.boot.handleEvent.service.impl;

import com.boot.handleEvent.Factory.CropReceiveFactory;
import com.boot.handleEvent.entity.WxCropEventXml;
import com.boot.handleEvent.enums.CropReceiveEvent;
import com.boot.handleEvent.service.ICropReceiveEventService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

/**
 * @Author: laz
 * @CreateTime: 2022-09-22  15:12
 * @Version: 1.0
 */
@Service("delExternalContactServiceImpl")
@Slf4j
public class DelExternalContactServiceImpl implements ICropReceiveEventService {

    /**
     * 类一加载 将当前对象转入map
     * @param delExternalContactService
     */
    @Autowired
    @Qualifier("delExternalContactServiceImpl")
    private void register(ICropReceiveEventService delExternalContactService) {
        CropReceiveFactory.set(CropReceiveEvent.DEL_EXTERNAL_CONTACT.value(),delExternalContactService);
    }

    @Override
    public void handleEvent(WxCropEventXml wxCropEventXml) {
        log.info("删除成员事件操作逻辑");
    }
}

事件类型枚举类:

package com.boot.handleEvent.enums;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 事件类型
 */
public enum CropReceiveEvent {



	/**
	 * 创建成员事件
	 */
	CREATE_USER("create_user","创建成员事件"),
	/**
	 * 更新成员事件
	 */
	UPDATE_USER("update_user","更新成员事件"),

	/**
	 * 删除客户事件
	 */
	DEL_EXTERNAL_CONTACT("del_external_contact","删除客户事件")
	;
	
	private String value;
	
	private String desc;

	private CropReceiveEvent(String value, String desc) {
		this.value = value;
		this.desc = desc;
	}

	public String value() {
		return value;
	}

	public String desc() {
		return desc;
	}

	public static String getDesc(String key) {
		if(key != null && VALUE_DESC_MAP.containsKey(key)){
			return VALUE_DESC_MAP.get(key);
		}
		return "";
	}

	private static final Map<String, String> VALUE_DESC_MAP = new ConcurrentHashMap<>();
	static {
		for (CropReceiveEvent item : CropReceiveEvent.values()) {
			VALUE_DESC_MAP.put(item.value(), item.desc());
		}
	}
	
}

客户事件消息内容实体类:

package com.boot.handleEvent.entity;

import java.io.Serializable;
import java.util.List;

import lombok.Data;

/**
 * 客户事件消息内容
 *
 * @Author: laz
 * @Date: 2022/1/14 10:33
 */
@Data
public class WxCropEventXml implements Serializable {
    private static final long serialVersionUID = 1L;

    /** 企业微信CorpID*/
    private String ToUserName;
    /** 成员UserID*/
    private String FromUserName;
    private String CreateTime;
    /** 消息类型*/
    private String MsgType;
    /** 事件类型*/
    private String Event;
    /** 事件类型*/
    private String ChangeType;
    /** 成员userid*/
    private String UserID;
    /** 外部联系人的userid*/
    private String ExternalUserID;
    /** 识别添加此用户的渠道*/
    private String State;
    /** 欢迎语code*/
    private String WelcomeCode;
    /** 删除客户的操作来源*/
    private String Source;
    /** 接替失败的原因*/
    private String FailReason;
    /** 群ID*/
    private String ChatId;
    /** 变更详情*/
    private String UpdateDetail;
    /** 入群方式*/
    private String JoinScene;
    /** 退群方式*/
    private String QuitScene;
    /** 成员变更数量*/
    private String MemChangeCnt;
    private String StrategyId;
    /** 标签类型*/
    private String TagType;
    /** 头像url */
    private String Avatar;
    /** 姓名*/
    private String Name;
    /** 性别*/
    private int Gender;
    private String Alias;
    /** 邮箱*/
    private String Email;
    /** 电话*/
    private String Telephone;
    /** 部门列表*/
    private List<Long> Department;
    /** 主部门*/
    private Long MainDepartment;

}

接收事件工厂:

package com.boot.handleEvent.Factory;

import java.util.LinkedHashMap;
import java.util.Map;

import com.boot.handleEvent.service.ICropReceiveEventService;
import org.springframework.stereotype.Component;

/**
 * @Author: laz
 * @Date: 2022/9/14 14:28
 */
@Component
public class CropReceiveFactory {

    private static Map<String, ICropReceiveEventService> cropReceiveEventMap = new LinkedHashMap<>();

    public static void set(String key,ICropReceiveEventService iCropReceiveEventService){
        cropReceiveEventMap.put(key,iCropReceiveEventService);
    }

    public static ICropReceiveEventService gethandleEventFactory(String key) {
        return cropReceiveEventMap.get(key);
    }

}

测试类:

package com.boot.handleEvent.controller;

import com.boot.handleEvent.Factory.CropReceiveFactory;
import com.boot.handleEvent.entity.WxCropEventXml;
import com.boot.handleEvent.service.ICropReceiveEventService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: laz
 * @CreateTime: 2022-09-22  15:30
 * @Version: 1.0
 */
@RestController
@RequestMapping("/test")
@RequiredArgsConstructor
public class Controller {


    @PostMapping("/receive")
    public Object receive(@RequestBody WxCropEventXml wxCropEventXml){
        ICropReceiveEventService iCropReceiveEventService = CropReceiveFactory.gethandleEventFactory(wxCropEventXml.getChangeType());
        iCropReceiveEventService.handleEvent(wxCropEventXml);
        return "访问成功";
    }

}

测试:
访问:http://localhost:8989/test/receive
参数:changeType值分别为create_user/update_user/del_external_contact
结果:
在这里插入图片描述
可以看到,根据changeType的不同,执行了对应的逻辑方法。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值