ArticleDirectory
- Overview
- Advantages
- Summary
Overview
Decorator pattern, also known as the decoration mode. The decoration mode dynamically extends the functions of an object without changing the original class file and using inheritance. It creates a packaging object, that is, decoration, to package a real object.
Let's first look at the UML class diagram structure of the decoration mode:
Advantages
- The decorator pattern dynamically adds some additional responsibilities to the object. In addition, the decorative pattern is more flexible than the production subclass.
- Use setcomponent to encapsulate objects. The implementation of each decoration object is separated from how to use this object. Each decoration object only cares about its own functions and does not need to be added to the object chain.
- You can remove the decoration function from the class to simplify the original class. This effectively separates the core responsibilities of the class from the decorative functional area. Besides, the repeated decoration logic in the related classes can be removed.
Summary
The decoration mode dynamically adds more functions to existing functions. When the system requires new functions, it adds new functions to the old class.Code. These new codes are usually decorated with the core responsibilities or main actions of the original class. Adding new fields, new methods, and new logic to the main class increases the complexity of the main class, the new things to be added only meet the needs of some special behaviors that can only be executed under specific circumstances. However, the decoration mode provides a very good solution. It puts every function to be decorated in a separate class and lets this class wrap the objects it needs to decorate. Therefore, when special behaviors need to be added, the client code can use the decoration function to wrap objects in order as needed during runtime.
Download with a click: Sample Code
References: big talk Design Model