mardi 28 juillet 2015

Command pattern implementation or adaption

I have different commands that all share some common data, so I extracted that to a super-class Command. All the concrete commands operate on an object of Foo when they implement the execute method. The actual invoker of the command is a client TheClient that creates a new object of the required command and directly executes it.

I have implemented it in such a way that the client and inovker is independent from the implementation details in the commands, and more importantly, independent from the class Foo.

I have the following questions:

1) Is this an implementation of the command pattern, or somehow an adoption of it?

2) From my understanding of the command pattern, in this example Foo is the receiver. Is this correct?

3) In contrast to the pure command pattern, I have merged the invoker and client into the same class. Some people say that this is OK in the command pattern, since both are a theoretical construct and in an actual implementation they can be in the same class. Is this correct?

public abstract class Command {
  protected String a;
  protected Foo foo;
  public Command(String a) {
    this.a = a;
    this.foo = new Foo(a);
  }
  public abstract void execute();
}

public class StartCommand extends Command {
  private String b;
  public StartCommand(String a, String b) {
    super(a);
    this.b = b;
  }
  public void execute() {
    this.foo.doSomething("start " + a + " with " + b);
  }
}

// ... other commands ...

public class Foo {
  protected String name;
  public Foo(String name) {
    this.name = name;
  }
  public void doSomething(String action) {
    // does something...
  }
}

public class TheClient {
  public static void main(String[] args) {
    Command command = new StartCommand("x", "y");
    command.execute();
  }
}

Aucun commentaire:

Enregistrer un commentaire