文章目录
package com.example.demo.designpattern;
public abstract class Command {
public abstract void execute();
}
class CommandA extends Command {
private Receiver receiver;
public CommandA(Receiver receiver) {
this.receiver = receiver;
}
@Override
public void execute() {
this.receiver.work();
}
}
class CommandB extends Command {
private Receiver receiver;
public CommandB(Receiver receiver) {
this.receiver = receiver;
}
@Override
public void execute() {
this.receiver.work();
}
}
class Invoker {
private Command command;
public Invoker(Command command) {
this.command = command;
}
public void setCommand(Command command) {
this.command = command;
}
public void action() {
this.command.execute();
}
}
abstract class Receiver {
public abstract void work();
}
class ReceiverA extends Receiver {
public void work() {
System.out.println("A-work");
}
}
class ReceiverB extends Receiver {
public void work() {
System.out.println("B-work");
}
}
class Client {
public static void main(String[] args) {
ReceiverA receiverA = new ReceiverA();
ReceiverB receiverB = new ReceiverB();
CommandA commandA = new CommandA(receiverA);
Invoker invoker = new Invoker(commandA);
invoker.action();
invoker.setCommand(new CommandB(receiverB));
invoker.action();
}
}