- Design Patterns and Best Practices in Java
- Kamalmeet Singh Adrian Ianculescu LUCIAN PAUL TORJE
- 326字
- 2021-06-25 20:52:36
Implementation
The class diagram of the command pattern is as follows:

We can distinguish the following actors in the preceding implementation diagram:
- Command: This is the abstraction that represents the encapsulation of a command. It declares the abstract method executed, which should be implemented by all the concrete commands.
- ConcreteCommand: This is the actual implementation of the Command. It has to execute the command and deal with the parameters associated with each concrete command. It delegates the command to the receiver.
- Receiver: This is the class responsible for executing the action associated with the command.
- Invoker: This is the class that triggers the command. This is usually an external event, such as a user action.
- Client: This is the actual class that instantiates the concrete command objects and their receivers.
Initially, our impulse is to deal with all possible commands in a big if-else block:
public void performAction(ActionEvent e)
{
Object obj = e.getSource();
if (obj = fileNewMenuItem)
doFileNewAction();
else if (obj = fileOpenMenuItem)
doFileOpenAction();
else if (obj = fileOpenRecentMenuItem)
doFileOpenRecentAction();
else if (obj = fileSaveMenuItem)
doFileSaveAction();
}
However, we may decide to apply the command pattern for the drawing application. We start by creating a command interface:
public interface Command
{
public void execute();
}
The next step is to define all the objects, such as menu items and buttons, as classes, implementing the command interface and the execute() method:
public class OpenMenuItem extends JMenuItem implements Command
{
public void execute()
{
// code to open a document
}
}
After we have repeated the previous operation, creating a class for each possible action, we replace the if-else block from the naive implementation with the following one:
public void performAction(ActionEvent e)
{
Command command = (Command)e.getSource();
command.execute();
}
We can see from our code that the invoker (the client that triggers the performAction method) and the receivers (the classes implementing the command interface) are decoupled. We can easily extend our code without changing it.
- Node.js 10實戰(zhàn)
- 華為HMS生態(tài)與應(yīng)用開發(fā)實戰(zhàn)
- Mastering Julia
- Python機器學(xué)習(xí)實戰(zhàn)
- 手把手教你學(xué)C語言
- Responsive Web Design by Example
- C語言程序設(shè)計教程
- C專家編程
- JBoss:Developer's Guide
- 零基礎(chǔ)學(xué)Scratch 3.0編程
- INSTANT Apache ServiceMix How-to
- 精通Spring:Java Web開發(fā)與Spring Boot高級功能
- 會當(dāng)凌絕頂:Java開發(fā)修行實錄
- Java Web動態(tài)網(wǎng)站開發(fā)(第2版·微課版)
- 從零開始學(xué)算法:基于Python