lundi 15 janvier 2018

Java what design pattern should I use for object instantiation if I have different constructor but same interface?

I'm learning about the design patterns and I encountered a problem which I cant resolve. I'm writing a client/server script. The administrator client send a task with its task data in json format, and the server should instantiate an object accordingly to the recieved task type, and fill its constructor with correct classes. As you can see bellow there are two example class.

public class StartProcessing implements ITask{
    private final IProcessor dataProcessor;

    public StartProcessing(IProcessor dataProcessor){
        this.dataProcessor = dataProcessor;
    }

    @Override
    public void ProcessTask() {
        this.dataProcessor.StartProcess();
    }

}

public class StartQueueFiller implements ITask{

    private IQueueFiller queueFiller;

    public StartQueueFiller(IQueueFiller queueFiller){
        this.queueFiller = queueFiller;
    }

    @Override
    public void ProcessTask() {
        this.queueFiller.Start();
    }

}

interface ITask {
    public void ProcessTask();
}

I've tried something like this, but I'll have like 50 different process and hundreds of tasks, so the constructor will be unmanageable, and I think the factory pattern is not so good in this case, and probably I just miss the point of the pattern. So how you would solve this problem? What should I use instead of the factory pattern?

public class TaskFactory(){

    private final IProcessor processor;
    private final IQueueFiller queuefiller;

    public TaskFactory(IProcessor processor, IQueueFiller queuefiller){
        this.processor = processor;
        this.queuefiller = queuefiller;
    }

    public ITaskCreate(String task){
        switch(task){
            case "startprocessor":
                return new StartProcessing(this.processor);
            case "startqueuefiller":
                return new StartQueueFiller(this.queuefiller);
        }
    }

}

Aucun commentaire:

Enregistrer un commentaire