开发者

Java: Simple implementation of Command pattern with onComplete callback?

Could someone point out where to find an implementation of the Command pattern with onComplete callback开发者_如何学Gos that could be used for example in a serial macro command?


Try this

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();

or this

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();

Examples of usage isn't from real life. Probably, you should separate creation and calling execution via creation CommandManager .

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜