Introduction to composite pattern of Java design pattern

Composite definition: organize objects in a tree structure to achieve a "part whole" hierarchical structure, so that the client can use single objects and composite objects consistently.

Composite is easy to understand. When you think of composite, you should think of tree structure diagram. These objects in the assembly have common interfaces. When the method of an object in the assembly is called and executed, the composite will traverse the whole tree structure, find the object that also contains this method, and implement the call and execution. It can be described as pulling a hundred.

Therefore, the composite mode uses the iterator mode, which is similar to the chain of responsibility mode.

Composite benefits:

1. Make the client call simple. The client can consistently use the composite structure or a single object, so the user does not have to deal with a single object or the whole composite structure, which simplifies the client code. 2. It is easier to add object parts into the assembly. The client does not have to change the code because a new object part is added.

How to use composite

First, define an interface or abstract class, which is the general way of design patterns. Other design patterns have few restrictions on the internal definition of interfaces, but composite has a provision, that is, define an object (or component) used to access and manage the composite assembly within the interface.

The following code is defined by abstract classes. Generally, try to use interface.

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
分享
二维码
< <上一篇
下一篇>>