Introduction to decorator pattern of Java design pattern

Decorator is often translated into "decoration". I think it is more vivid to translate it into "painter". Painter is used to brush paint, so the object to be painted is called decoratee. These two entities are required in the decorator pattern.

Decorator definition: dynamically add some additional responsibilities to an object, such as painting a wall. It is more flexible to use decorator mode to expand functions than to generate subclasses.

Why use decorator

We can usually use inheritance to expand functions. If there are many kinds of functions to be expanded, it is bound to generate many subclasses and increase the complexity of the system. At the same time, we must foresee these expanded functions. These functions are determined at compile time and are static.

The reason for using decorator is that these functions need to be dynamically determined by the user. Decorator provides a "plug and play" method to decide when and what functions to add during operation.

How to use decoration mode

Take the piling example in the adapter. In the adapter, there are two types: square pile and circular pile. The adapter mode shows how to comprehensively use these two classes. In the decorator mode, we want to add some additional functions during piling, such as digging a pit and nailing a board on the pile. We don't care about how to use two unrelated classes.

Let's first establish an 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
分享
二维码
< <上一篇
下一篇>>