命令模式

一、类图:

屏幕快照 2019-07-30 上午8.39.37.png

二、示例代码:

public interface Command {
    public void execute();
    public void undo();
}


public class Receiver {
    public void doSomething(){
        System.out.println("receiver do something.");
    }
    public void undoSomething(){
        System.out.println("receiver undo something.");
    }
}

public class ConcreteCommandA implements Command {
    private Receiver receiver;

    public ConcreteCommandA(Receiver receiver) {
        this.receiver = receiver;
    }

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

    @Override
    public void undo() {
        receiver.undoSomething();
    }
}


public class Invoker {
    private Stack undoStack=new Stack<>();

    public void invoke(Command command){
        undoStack.push(command);
        command.execute();
    }
    public void undoCommnad(){
        undoStack.pop().undo();
    }
}

测试用例(Client角色)

import org.junit.Before;
import org.junit.Test;

public class CommandTest {
    private Receiver receiver;
    private Command commandA;
    //若干receiver和command
    //...
    private Invoker invoker;
    @Before
    public void before(){
        receiver=new Receiver();
        commandA=new ConcreteCommandA(receiver);
        invoker=new Invoker();

    }

    @Test
    public void testCommand(){
        invoker.invoke(commandA);
        invoker.invoke(commandA);
        invoker.undoCommnad();
        invoker.undoCommnad();
    }
}

你可能感兴趣的:(命令模式)