命令模式相较于直接绑定按钮动作的实际代码优势探讨
命令模式相较于直接绑定按钮动作的实际代码优势探讨
There is something that I couldn't understand regarding the command pattern.
What is the advantage of using the Command pattern compared to directly assigning actions to buttons?
Let me demonstrate it with the following example.
// receiver class Document { public void save() {} public void open() {} } interface Command{ void execute(); } // Concrete Commands class SaveCommand implements Command { private Document document; public SaveCommand(Document document) { this.document = document; } @Override public void execute() { document.save(); } } class OpenCommand implements Command { private Document document; public OpenCommand(Document document) { this.document = document; } @Override public void execute() { document.open(); } } // Invoker: Generic Button class Button { private Command command; public void setCommand(Command command) { this.command = command; } public void execute() { command.execute(); } } // Client Code public class Main{ public static void main(String[] args) { // Receiver: Document Document document = new Document(); // Commands Command saveCommand = new SaveCommand(document); Command openCommand = new OpenCommand(document); // Buttons (Invokers) Button saveButton = new Button(saveCommand); Button openButton = new Button(openCommand ); saveButton.execute(); openButton.execute(); } }
What is the edge that this command pattern gives us over this approach?
class Document { public void save() {} public void open() {} } interface Button { public void execute(); } class SaveButton implements Button{ private Document document; public SaveButton (Document document) { this.document = document; } @Override public void execute() { document.save(); } } class OpenButton implements Button{ private Document document; public OpenButton (Document document) { this.document = document; } @Override public void execute() { document.open(); } } // Client Code public class Main{ public static void main(String[] args) { // Receiver: Document Document document = new Document(); // Buttons (Invokers) Button saveButton = new SaveButton(document); Button openButton = new OpenButton(document); saveButton.execute(); openButton.execute(); } }
In both cases, the buttons are separated from the logic. My question is: What is the benefit of the extra Command layer in the first example? How does using the Command pattern improve this situation over directly binding the actions to buttons as shown in the second example?
What is the benefit of it in code rather than just in theory?
备注:内容来源于stack exchange,提问作者Omar Saleh
相关产品推荐
相关产品推荐

