编程语言
首页 > 编程语言> > 【Java设计模式】命令模式

【Java设计模式】命令模式

作者:互联网

【定义】

对命令进行抽插式设计,使用Invoker发起指定Command对Receiver方法的调用。

【实现】

创建命令接口:

interface ICommand
{
    void Do();
}

创建实际的重做命令与撤销命令:

class MyUndoCommand implements ICommand
{
    private Receiver receiver;
    MyUndoCommand(Receiver recv)
    {
        receiver=recv;
    }
    @Override
    public void Do()
    {
        //Call undo in receiver
        receiver.performUndo();
    }
}
class MyRedoCommand implements ICommand
{
    private Receiver receiver;
    MyRedoCommand(Receiver recv)
    {
        receiver=recv;
    }
    @Override
    public void Do()
    {
        //Call redo in receiver
        receiver.performRedo();
    }
}

实际的操作都是Receiver在做:

class Receiver
{
    public void performUndo()
    {
        System.out.println("Executing -MyUndoCommand");
    }
    public void performRedo()
    {
        System.out.println("Executing -MyRedoCommand");
    }
}

调用命令:

class Invoke
{
    ICommand cmd;
    public void ExecuteCommand(ICommand cmd)
    {
        this.cmd=cmd;
        cmd.Do();
    }
}

测试:

 

 

标签:ICommand,cmd,Java,void,receiver,模式,Receiver,设计模式,public
来源: https://blog.csdn.net/Day_and_Night_2017/article/details/98480785