有人会指出在哪里可以使用onComplete回调找到Command模式的实现,例如在串行宏命令中可以使用?
纳斯
答案 0 :(得分:8)
试试这个
abstract class Command {
final public void execute(){
run();
onComplete();
}
protected abstract void run();
protected abstract void onComplete();
}
//usage
abstract class HiCommand extends Command {
protected void run(){
System.out.println("Hi, ");
}
protected abstract void onComplete();
}
new HiCommand(){
@Override
protected void onComplete() {
System.out.println("world");
}
}.execute();
或者
interface WhenDone{
void onComplete();
}
abstract class Command {
private final WhenDone callback;
protected Command(WhenDone callback){
this.callback = callback;
}
final public void execute(){
run();
callback.onComplete();
}
protected abstract void run();
}
//usage
class PrintHi extends Command {
protected PrintHi(WhenDone callback){
super(callback);
}
protected void run(){
System.out.println("Hi, ");
}
}
class PrintWorld implements WhenDone {
public void onComplete(){
System.out.println("world!");
}
}
//somewhere
new PrintHi(new PrintWorld()).execute();
使用的例子不是来自现实生活。也许,您应该通过创建CommandManager
来分离创建和调用执行。