Java, which design pattern should I use to create an object if I have a different constructor but the same interface?

I study design patterns and I have a problem that I cannot solve. I am writing a client / server script. The administrator client sends a task with the data of its task in json format, and the server must create an instance of the object in accordance with the type of task received and fill its constructor with the correct classes. As you can see below, there are two class examples.

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();
}

- , 50 , , , factory , , . , ? factory?

public class TaskFactory(){

    private final IProcessor processor;
    private final IQueueFiller queuefiller;

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

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

}
+4
1

Abstract Factory:

public interface TaskFactory {
    Task create();
}

- , :

private final Map<String, TaskFactory> factoriesMap = new HashMap<>();

void registerFactory(String identifier, TaskFactory factory) {
    factoriesMap.put(identifier, factory);
}

public Task create(String identifier) {
    return factoriesMap.get(identifier).create();
}

, -:

Processor processor = ...;
registerFactory("startprocessor", () -> new StartProcessingTask(processor));

.

- , "factory " , , . . DI TaskFactory . , factory -like (, " " ).

+5

Source: https://habr.com/ru/post/1692216/


All Articles