ExperimentFactory.java 1.68 KB
package com.example.mina.client.base;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.Map;

@Slf4j
public abstract class ExperimentFactory < T extends Experiment> {

    private Map<String, T> experiments;

    public ExperimentFactory() {
        experiments = CollectionUtils.newHashMap(10);
    }

    public T getExperiment(String matrixId) {

        return experiments.getOrDefault(matrixId, null);
    }

    public void stopExperiment(String matrixId) {
        T t = getExperiment(matrixId);

        if( t != null && t.isContinue()){
            t.finish();
            experiments.remove(matrixId);
        }
    }

    abstract public boolean isSupport();

    abstract Class<T> getClazz();

    public ExperimentProgressListner getListner() {
        return null;  //TODO 生成任务进度更新监听器
    }

    public T createExperiment(MatrixClient client, ExperimentOptions options){

        if(isSupport()) {
            log.error("the experiment is not supported by the matrix! matrix id: " + client.getDeviceId());
            throw new RuntimeException("the experiment is not supported by the matrix! matrix id: " + client.getDeviceId());
        }

        Class<T> tClass = getClazz();

        try{

            T t = tClass.newInstance();

            t.setClient(client);
            t.setOptions(options);
            t.setProgressListner(getListner());
            return t;
        }catch (Exception e) {
            log.error("create a experiment task is failed, matrix id: " + client.getDeviceId());
            throw new RuntimeException("create a experiment task is failed, matrix id: " + client.getDeviceId());
        }
    }

}