package command_pattern;
public abstract class Command {
protected Receiver receiver;
public Command(Receiver receiver) {
this.receiver = receiver;
}
public abstract void executed();
}
package command_pattern;
public class ConcreteCommand extends Command{
public ConcreteCommand(Receiver receiver) {
super(receiver);
}
@Override
public void executed() {
receiver.action();//Give the command to receiver.
}
}
package command_pattern;
public class Receiver {
public void action() {
System.out.println("Executed the request.");
}
}
package command_pattern;
public class Invoker {
private Command command;//It can gather a set of commands to execute together
//through using ArrayList<T>.
public void setCommand(Command command) {
this.command = command;
}
public void executedCommand() {
command.executed();
}
}
package command_pattern;
public class Main {
public static void main(String args[]) {
Receiver r = new Receiver();
Command c = new ConcreteCommand(r);//Map the command and receiver together.
Invoker i = new Invoker();
i.setCommand(c);//Invoker composites the command so as to invoke different
//command.The super class command composite the receiver so as to send the
//command to the related receiver.
i.executedCommand();
}
}
This is a general introduction to the 23 design patterns:
https://blog.youkuaiyun.com/GZHarryAnonymous/article/details/81567214
See more source code:[GZHarryAnonymous](https://github.com/GZHarryAnonymous/Design_Pattern)