设计模式 – 命令模式(Command Pattern)

内容纲要

命令模式(Command Pattern)是一种行为设计模式,它将请求封装成一个对象,从而使你可以将不同的请求参数化、队列化或记录请求日志,以及支持可撤销的操作。命令模式通常用于实现“undo”和“redo”功能,或者在构建宏命令和任务队列时使用。

Java 示例代码:

首先,我们创建一个命令接口:

public interface Command {
    void execute();

    void undo();
}

接下来,我们创建一个接收者类,它定义了一些操作:

public class Receiver {
    public void actionA() {
        System.out.println("Action A is executed.");
    }

    public void actionB() {
        System.out.println("Action B is executed.");
    }
}

然后,我们创建具体的命令类,实现 Command 接口,并与接收者对象交互:

public class ConcreteCommandA implements Command {
    private Receiver receiver;

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

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

    @Override
    public void undo() {
        System.out.println("Undo Action A.");
    }
}

public class ConcreteCommandB implements Command {
    private Receiver receiver;

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

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

    @Override
    public void undo() {
        System.out.println("Undo Action B.");
    }
}

现在,我们创建一个调用者类,它将命令对象作为参数并执行它们:

public class Invoker {
    private Command command;

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

    public void executeCommand() {
        if (command != null) {
            command.execute();
        }
    }

    public void undoCommand() {
        if (command != null) {
            command.undo();
        }
    }
}

最后,我们可以在客户端代码中使用这些类:

public class Client {
    public static void main(String[] args) {
        // 创建接收者
        Receiver receiver = new Receiver();

        // 创建命令对象
        Command commandA = new ConcreteCommandA(receiver);
        Command commandB = new ConcreteCommandB(receiver);

        // 创建调用者并设置命令对象
        Invoker invoker = new Invoker();
        invoker.setCommand(commandA);
        invoker.executeCommand();

        invoker.setCommand(commandB);
        invoker.executeCommand();
    }
}

输出:

Action A is executed.
Action B is executed.

通过这个示例,你可以看到命令模式如何将请求封装成一个对象,使

Leave a Comment

您的电子邮箱地址不会被公开。 必填项已用*标注

close
arrow_upward