设计模式-工厂模式+策略模式

由于现如今都是使用spingboot框架,这么现在就是基于springboot来实现工厂模式+策略模式

为了防止大量的if…else…或switch case代码的出现,可以使用策略模式+工厂模式进行优化。
在我的项目当中,报表繁多,所以尝试了这种方式进行优化报表的架构。代码很简单,如下:

工厂模式+策略模式-低配版

Factory工厂类

@Service
public class ReportFactory {

    /**
     * 初始化的时候将所有的ReportService自动加载到Map中
     */
    @Autowired
    private final Map<String, ReportService> reportIns = new ConcurrentHashMap<>();

    public ReportService getReportIns(String code) {
        ReportService reportInstance = reportIns.get(code);
        if (reportInstance == null) {
            throw new RuntimeException("未定义reportInstance");
        }

        return reportInstance;
    }

}

接口

public interface ReportService {
    String getResult();
}

实现类

@Component(value = "A1")
public class ReportServiceA1 implements ReportService {

    @Override
    public String getResult() {
        return "我是A1";
    }
}
@Component(value = "A2")
public class ReportServiceA2 implements ReportService {

    @Override
    public String getResult() {
        return "我是A2";
    }
}

测试

@SpringBootTest
public class BlogServerApplicationTest {

    @Autowired
    ReportFactory reportFactory;

    @Test
    public void test2() {
        String result1 = reportFactory.getReportIns("A1").getResult();
        System.out.println("-----------------");
        System.out.println(result1);
        String result2 = reportFactory.getReportIns("A2").getResult();
        System.out.println("-----------------");
        System.out.println(result2);
    }
}

打印如下:

-----------------
我是A1
-----------------
我是A2

工厂模式+策略模式-高配版

在这里插入图片描述

接口

package com.tasksupervison.strategy;

import java.util.Map;

/**
 * @author chendong
 * @date 2020-11-05 14:28
 * @Description:
 */
public interface IPushNotificationStrategy {

    /**
     * 推送消息
     *
     * @param params
     */
    void pushMsg(Map<String, Object> params);
}

自定义注解

package com.tasksupervison.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author chendong
 * @date 2020-11-05 14:40
 * @Description:
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface PushNote {

    /**
     * 类型
     *
     * @return
     */
    String value();
}

工厂实现类

package com.tasksupervison.strategy;/**
 * @author chendong
 * @date 2020-11-05 14:41
 * @Description:
 */

import com.izkml.mlyun.tasksupervison.annotation.PushNote;
import com.izkml.mlyun.tasksupervison.util.BeansUtil;
import org.reflections.Reflections;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author chendong
 * @date 2020-11-05 14:41
 * @Description:
 */
@Component
public class PushNoteStrategyFactory {

    private static final String STRATEGY_IMPLEMENTATION_PACKAGE = "com.izkml.mlyun.tasksupervison.strategy";
    private static final Map<String, Class> STRATEGY_MAP = new HashMap<>();


    private PushNoteStrategyFactory() {
    }

    // 获取所有策略
    static {
        Reflections reflections = new Reflections(STRATEGY_IMPLEMENTATION_PACKAGE);
        Set<Class<?>> classSet = reflections.getTypesAnnotatedWith(PushNote.class);
        classSet.forEach(aClass -> {
            PushNote annotation = aClass.getAnnotation(PushNote.class);
            STRATEGY_MAP.put(annotation.value(), aClass);
        });
    }

    /**
     * 根据策略类型获取策略bean
     *
     * @param type
     * @return
     */
    public static IPushNotificationStrategy getStrategy(String type) {
        // 反射获取策略实现类clazz
        Class clazz = STRATEGY_MAP.get(type);
        if (StringUtils.isEmpty(clazz)) {
            return null;
        }

        // 通过applicationContext获取bean
        return (IPushNotificationStrategy) BeansUtil.getBean(clazz);
    }
}

抽象实现类

package com.tasksupervison.strategy;

import com.alibaba.fastjson.JSONObject;
import com.izkml.mlyun.tasksupervison.constant.NotificationRequest;
import com.izkml.mlyun.tasksupervison.constant.SystemConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.SimpleMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.task.TaskExecutor;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author chendong
 * @date 2020-11-05 14:35
 * @Description: 推送消息策略抽象类
 */
@Slf4j
public abstract class AbstractPushNotificationStrategy implements IPushNotificationStrategy {

    @Autowired
    private TaskExecutor taskExecutor;

    private static final String LINK_PREFIX = "http://";

    @Value("${gateway.ip}")
    private String GATEWAY_IP;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 自定义方法
     *
     * @param params
     * @return
     */
    protected abstract NotificationRequest getBaseMsgData(Map<String, Object> params);

    /**
     * 自定义方法
     *
     * @param params
     * @return
     */
    protected abstract List<String> getDestIds(Map<String, Object> params);

    @Override
    public void pushMsg(Map<String, Object> params) {
        // 线程池异步推送
        taskExecutor.execute(() -> {

            NotificationRequest request = this.getBaseMsgData(params);

            // 获取推送目标,并转换格式
            String destIds = this.getDestIds(params).stream().reduce((x, y) -> x + "|" + y).get();
            request.setDestId(destIds);

            // 设置推送时间
            if (request.getPublishTime() == null) {
                request.setPublishTime(new Date());
            }
            // 推送到MQ
            String mqMsg = JSONObject.toJSONString(request);
            log.info("推送消息 ========================= {}", mqMsg);
            rabbitTemplate.setMessageConverter(new SimpleMessageConverter());
            rabbitTemplate.convertAndSend(SystemConstant.GOV_WORKBENCH_DIRECT_EXCHANGE, SystemConstant.GOV_WORKBENCH_NOTIFICATION, mqMsg);
        });
    }
}

具体实现类

package com.tasksupervison.strategy;

import com.izkml.mlyun.tasksupervison.annotation.PushNote;
import com.izkml.mlyun.tasksupervison.constant.NotificationRequest;
import com.izkml.mlyun.tasksupervison.constant.PushNoteBizConstant;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author chendong
 * @date 2020-11-05 14:51
 * @Description: 汇报到期提醒
 */
@Component
@PushNote(PushNoteBizConstant.REMIND_DEADLINE)
public class PushRemindDeadlineStrategy extends AbstractPushNotificationStrategy {
    @Value("${message.jump.addr}")
    private String JUMP_URL;

    @Override
    protected NotificationRequest getBaseMsgData(Map<String, Object> params) {
        NotificationRequest request = new NotificationRequest();
        request.setDestType("STAFF");
        request.setGroupType("JG.RWDB");
        request.setTitle("任务到期提醒");
        request.setLink(JUMP_URL);
        request.setJumpWay("GET");
        request.setContent("任务即将到期,请及时办理完成。");
        request.setDescription("任务即将到期,请及时办理完成。");
        request.setPublisherType("STAFF");
        request.setPublishTime(new Date());
        return request;
    }

    @Override
    protected List<String> getDestIds(Map<String, Object> params) {
        List<String> list = (List<String>) params.get("receiverId");
        return list;
    }
}

package com.tasksupervison.strategy;

import com.izkml.mlyun.tasksupervison.annotation.PushNote;
import com.izkml.mlyun.tasksupervison.constant.NotificationRequest;
import com.izkml.mlyun.tasksupervison.constant.PushNoteBizConstant;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author chendong
 * @date 2020-11-05 14:51
 * @Description: 提醒汇报
 */
@Component
@PushNote(PushNoteBizConstant.REMIND_REPORT)
public class PushRemindReportStrategy extends AbstractPushNotificationStrategy {
    @Value("${message.jump.addr}")
    private String JUMP_URL;
    @Override
    protected NotificationRequest getBaseMsgData(Map<String, Object> params) {
        NotificationRequest request = new NotificationRequest();
        request.setDestType("STAFF");
        request.setGroupType("JG.RWDB");
        request.setTitle("汇报提醒");
        request.setLink(JUMP_URL);
        request.setJumpWay("GET");
        request.setContent(params.get("content").toString());
        request.setDescription(params.get("content").toString());
        request.setPublisherType("STAFF");
        request.setPublishTime(new Date());
        return request;
    }

    @Override
    protected List<String> getDestIds(Map<String, Object> params) {
        List<String> list = (List<String>) params.get("receiverId");
        return list;
    }
}

package com.tasksupervison.strategy;/**
 * @author chendong
 * @date 2020-11-05 14:51
 * @Description:
 */

import com.izkml.mlyun.tasksupervison.annotation.PushNote;
import com.izkml.mlyun.tasksupervison.constant.NotificationRequest;
import com.izkml.mlyun.tasksupervison.constant.PushNoteBizConstant;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author chendong
 * @date 2020-11-05 14:51
 * @Description:
 */
@Component
@PushNote(PushNoteBizConstant.URGE_HANDLE)
public class PushUrgeHandleStrategy extends AbstractPushNotificationStrategy {
    @Value("${message.jump.addr}")
    private String JUMP_URL;

    @Override
    protected NotificationRequest getBaseMsgData(Map<String, Object> params) {
        NotificationRequest request = new NotificationRequest();
        request.setDestType("STAFF");
        request.setGroupType("JG.RWDB");
        request.setTitle("催办提醒");
        request.setLink(JUMP_URL);
        request.setJumpWay("GET");
        request.setPublisherId(params.get("publisherId").toString());
        request.setContent(params.get("content").toString());
        request.setDescription(params.get("content").toString());
        request.setPublisherType("STAFF");
        request.setPublishTime(new Date());
        return request;
    }

    @Override
    protected List<String> getDestIds(Map<String, Object> params) {
        List<String> list = (List<String>) params.get("receiverId");
        return list;
    }
}

在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值