All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.lulihu.disruptorKit.oneOf.WorkHandlerManage Maven / Gradle / Ivy

package net.lulihu.disruptorKit.oneOf;

import net.lulihu.Assert0;
import net.lulihu.designPattern.chain.ResponsibilityChainHandler;

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

/**
 * 不重复消费者管理器
 */
public class WorkHandlerManage {

    private final Map, ResponsibilityChainHandler> handlerMap;

    private WorkHandlerManage() {
        handlerMap = new HashMap<>();
    }

    /**
     * 获取实例
     */
    public static WorkHandlerManage getInstance() {
        return WorkHandlerManageEnum.INSTANCE.getWorkHandlerManage();
    }

    /**
     * 添加处理程序至工作消费者
     *
     * @param name    名称
     * @param handler 处理程序
     */
    public synchronized  void addWorkHandler(Class name, ResponsibilityChainHandler handler) {
        Assert0.toolBox()
                .notNull(name, "处理程序类型不可为空")
                .notNull(handler, "处理程序不可为空")
                .notTrue(handlerMap.containsKey(name), "已经存在指定类型的处理程序");
        handlerMap.put(name, handler);
    }


    /**
     * 获取处理程序
     *
     * @param name 名称
     * @return 指定的处理程序
     */
    public ResponsibilityChainHandler getWorkHandler(Class name) {
        Assert0.toolBox().notTrue(!handlerMap.containsKey(name), "不存在指定类型的处理程序");
        return handlerMap.get(name);
    }

    /**
     * 生成指定数量的消费者消费者
     */
    public WorkHandlerConsumer[] consumerNum(int num) {
        WorkHandlerConsumer[] consumers = new WorkHandlerConsumer[num];
        for (int i = 0; i < num; i++) {
            consumers[i] = new WorkHandlerConsumer();
        }
        return consumers;
    }

    /**
     * 利用枚举实现 单例
     */
    private enum WorkHandlerManageEnum {

        INSTANCE;

        WorkHandlerManage workHandlerManage = new WorkHandlerManage();

        WorkHandlerManageEnum() {
        }

        public WorkHandlerManage getWorkHandlerManage() {
            return this.workHandlerManage;
        }

    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy