[Design Mode random link] - Command Mode

1. Why should command mode

  1. Software build process. Requester behavior and the behavior of the caller may have a case of strong coupling. As follows
    if (type == a) { do_a() }
    else if (type == b) { do_b() }
    else if (type == c) { do_c() }
    ...

    This code is very complicated and high coupling, it is necessary to optimize a pattern out of it.

  2. You may need to be withdrawn behavior and other operations, such coding can be very troublesome.

So, command mode, to do is to conduct packaged as an object , in order to solve this problem.

2. Definition command mode

Command mode:

The request (behavior) encapsulated into objects, to use different requests, the queue of log parameters or other objects, may support operations can be revoked.

3. The realization of command mode

First, we should define the command interface.

public interface Command {
    public void execute();
}

If this series of commands need to undo, you can undo and then define a method.

Then, subclass By implementing it, constitute a different command.

public class TestCommand {
    public void execute() {
        doSomething();
    }
}

Finally, the caller by passing the Command object implementation calls.

 

Guess you like

Origin www.cnblogs.com/tomoka/p/10985661.html