Right way to compose an action as a sequence of multiple smaller actions?

276 Views Asked by At

I have three actions defined like so:

public class A extends AbstractAction;
public class B extends AbstractAction;
public class C extends AbstractAction;

Now I want to define a jumbo action that does these three actions in order. I am sure there is a better way to do this than to do the following:

public class JumboAction extends AbstractAction {

  ...

  public void actionPerformed(ActionEvent e) {
    new A().actionPerformed(null);
    new B().actionPerformed(null);
    new C().actionPerformed(null);
  }
}

I just dont know what the better way is. Can someone please point me to that?


To add more context as suggested in answers, my application has some UI elements (like nodes and edges), and the user can select a bunch of nodes and perform A, B, C, or JumboAction on them.

3

There are 3 best solutions below

3
Hovercraft Full Of Eels On

This idea of one control calling others as you're doing doesn't smell right to me, as if you're confusing the control with the model (ignoring also your use of null for the ActionEvents). The control should change the state of the model by calling model methods. Why not have your jumbo control call three (or more) model methods or whatever else is required, in order to complete its needs.

Perhaps you can give us a better understanding of your problem by giving more information about the concrete specifics of your problem as they may be just as or more important than the abstract ideas.

0
Cannon Palms On

The way you're doing it is just fine.

The only thing I would do differently is replace actionPerformed(null) with actionPerformed(e). This would allow for A, B, and C to access the ActionEvent in context.

edit: If actions A, B, and C were not intended to be used individually as well, I would recommend combining the actions into three methods within the JumboAction class.

0
Thihara On

It seem to me that you are going outside the purpose of the Action classes because you are passing null to the actionPerformed methods.

Consider encapsulating your execution logic (business or otherwise) in a separate set of classes class and call those from the actions.

It will remove the need to duplicate the code and give you cleaner Action classes that do what they are supposed to do.

You can if you wish to use the same order have another method calling the business logic classes in an pre defined order.

Also check out the Command pattern, particularly the macro command area. Perhaps you can benefit from some adaptation of that.