Introduction to command mode of Java design pattern

Command mode is the one that puzzles me most. After reading a lot of code, I feel that I vaguely master its general principle. I think the most important thing to understand design mode is to master the principle structure, which can guide my actual programming. In fact, the command mode is not very specific and provides many modes. It is this flexibility that makes people confused.

Command definition

Many command mode codes are aimed at the graphical interface. It is actually a menu command. When we select a command from a drop-down menu, we will perform some actions.

Encapsulate these commands into a class, and then the user (caller) operates on this class. This is the command mode. In other words, the user (caller) calls these commands directly. For example, when you open a document (caller) on the menu, you directly point to the code that opens the document. Using the command mode is to add an intermediary between the two, This direct relationship is broken, and both are isolated, which is basically irrelevant.

Obviously, the advantage of this is to comply with the characteristics of encapsulation and reduce the degree of coupling. Command is a typical pattern that encapsulates behavior, and factory is a pattern that will be created for encapsulation.

From the command pattern, I also found a "common problem" in the design pattern: I seem to like to complicate simple problems and add a third party in different classes. Of course, this is conducive to the robustness, maintainability and reusability of the code.

How to use command mode

The specific command mode codes are various, because different systems have different ways to encapsulate commands. In the following example, the command is encapsulated in a collection list. Once any object is added to the list, it is actually loaded into a closed black box, and the characteristics of the object disappear. Only when it is taken out can it be vaguely distinguished.

A typical command mode requires an interface. There is a unified method in the interface, which is "encapsulating commands / requests as objects":

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>