08

    科技2025-01-14  7

    GoF 定义:把一个请求封装为对象,通过传递不同的请求配置客户端,并允许撤销的操作。( Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.)

    命令模式中有4个概念:invoker、client、command、receiver.

    Command是命令的接口,command对象调用receiver中的方法,而receiver中的方法定义了具体的命令参数。

    Invoker 通过command接口执行命令,但不需要知道具体调用了什么命令操作。

    Clinet包含Invoker和Command,并决定什么时候调用什么命令。调用具体某个命令时,将对应的Command对象传递给Invoker.

    以下代码实现了上述4个主要组成:

    /** * Command patterns */ public class Main { public static void main(String[] args) { Receiver receiver = new Receiver(); RedoCmd redoCmd = new RedoCmd(receiver); UndoCmd undoCmd = new UndoCmd(receiver); // 执行undo命令 new Invoker(undoCmd).exec(); // 执行redo命令 new Invoker(redoCmd).exec(); } } // 命令接口 interface ICommand { void exec(); } // Receiver 类,命令参数的具体实现 class Receiver { void redo() { System.out.println("Execute REDO."); } void undo() { System.out.println("Execute UNDO."); } } // redo 命令类 class RedoCmd implements ICommand { private Receiver receiver; public RedoCmd(Receiver receiver) { this.receiver = receiver; } @Override public void exec() { receiver.redo(); } } // Undo 命令类 class UndoCmd implements ICommand { private Receiver receiver; public UndoCmd(Receiver receiver) { this.receiver = receiver; } @Override public void exec() { receiver.undo(); } } // invoker 类,通过ICommand方法执行命令,不需要知道具体执行了什么命令 class Invoker { ICommand iCommand; public Invoker(ICommand iCommand) { this.iCommand = iCommand; } public void exec() { iCommand.exec(); } }

    代码结构:

    运行结果:

     

    后记:命令模式的主要作用是将【命令调用】与【命令具体参数和实现】分离,以便方便地扩展而不改变代码结构。

    Processed: 0.017, SQL: 8