Java设计模式泛型化之命令模式

时间:2021-04-27 19:24:11

简单理解就是:

司令->传令官->士兵

但是这里隐含了一些东西:

命令是怎样的?

它的基本结构是:

一个抽象的命令接口
一个抽象的命令执行者接口
一个统一调用类
几个具体的命令实现类
几个具体的命令执行者实现类
一个调用者

先看看代码:

抽象的命令执行者接口

public interface Executor {

public void doSomething();

public void doOtherthing();
}

具体的命令执行者实现类

public class ExecutorA implements Executor {

@Override
public void doSomething() {
System.out.println("Executor A do something.");
}

@Override
public void doOtherthing() {
System.out.println("Executor A do otherthing.");
}

}

public class ExecutorB implements Executor {

@Override
public void doSomething() {
System.out.println("Executor B do something.");
}

@Override
public void doOtherthing() {
System.out.println("Executor B other thing.");
}

}

抽象的命令接口

public abstract class Command {

protected Executor executorA = new ExecutorA();

protected Executor executorB = new ExecutorB();

public abstract void execute();
}

具体的命令实现类

public class CommandA extends Command {

@Override
public void execute() {
super.executorA.doSomething();
}

}

public class CommandB extends Command {

@Override
public void execute() {
super.executorB.doOtherthing();
}

}

统一调用类

public class Invoker {

private Command command;

public void setCommand(Command command) {
this.command = command;
}

public void doAction() {
command.execute();
}
}

调用者

public class CommandCaller {

public static void main(String[] args) {
Command ca = new CommandA();
Invoker in = new Invoker();
in.setCommand(ca);
in.doAction();
}
}

那么,如何泛型化呢?显然,Command是入口。泛型化代码如下:

抽象的命令接口

@SuppressWarnings("all")
public abstract class Command<T extends Executor> {

protected T t;

public Command(Class<? extends Executor> c) {
try {
t = (T) Class.forName(c.getName()).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}

public abstract void execute();
}

具体的命令接口实现类

public class CommandA<T extends Executor> extends Command<T> {

public CommandA(Class<? extends Executor> c) {
super(c);
}

@Override
public void execute() {
super.t.doSomething();
}

}

public class CommandB<T extends Executor> extends Command<T> {

public CommandB(Class<? extends Executor> c) {
super(c);
}

@Override
public void execute() {
super.t.doOtherthing();
}

}

统一调用类

public class Invoker<T extends Command<? extends Executor>> {

private T t;

public void setCommand(T t) {
this.t = t;
}

public void doAction() {
t.execute();
}
}

调用者

public class CommandCaller {

public static void main(String[] args) {
Command<ExecutorA> ca = new CommandA<ExecutorA>(ExecutorA.class);
Invoker<Command<ExecutorA>> in = new Invoker<Command<ExecutorA>>();
in.setCommand(ca);
in.doAction();
}
}