Search code examples
javadesign-patternscommand-pattern

Is this code some kind of command pattern?


I have a method that needs to execute multiple tasks to achieve a bigger task. Each task could be around 20-30 lines of code, so I decided to have a class per task.

public void bigTask() {
    TaskProcessor executor = new TaskProcessor();
    executor.addTask(new Task1(some arguments here));
    executor.addTask(new Task2(some other arguments here));
    executor.addTask(new Task2(some other arguments here));
    executor.run();
}

public interface Task {
    public void execute();
}

public class Task1 implements Task {
    @Override
    public void execute() {
        //Some code here
    }
}

public class Task2 implements Task {
    @Override
    public void execute() {
        //Some other code here
    }
}

public class Task3 implements Task {
    @Override
    public void execute() {
        //Some other code here
    }
}

public class TaskProcessor implements Serializable {

    private List<Task> tasksList;

    public TaskProcessor () {
        this.tasksList = new ArrayList<Task>();
    }

    public void addTask(Task task) {
        this.tasksList.add(task);
    }

    public void execute() {
        for (Task task : this.tasksList) {
            task.execute();
        }
    }
}

For me, this code is like a command pattern, but I am not sure because the arguments for each task are of different types, unlike the traditional command pattern.

Do you think this could be considered a command pattern implementation? Do you think this approach is OK for splitting a big method?

Thank you


Solution

  • Do you think this could be considered a command pattern implementation?

    I think it is "command pattern" enough.

    Do you think this approach is OK for splitting a big method?

    We used a very similar approach to dissect long "sequences" small "Actions". But we added different kind of "containers". As in: sometimes I have a sequence of Actions that should continue to be executed, even when one entry fails. In other cases, the whole sequence should stop immediately. Another flavor is a sequence where each Action also has a an undo() method, so that the sequence container can do a rollback of all previous (passed) Actions when some Action fails.

    Depending on your context, you might be "good to go", but I think you should at least consider what/if your indvidual Tasks can fail, and how your TaskProcessor container should react to failing steps.