Design Patterns: Study Notes (8) - Decorator Pattern
quick start
introduce
The Decorator Pattern allows adding new functionality to an existing object without changing its structure . This type of design pattern is a structural pattern, which acts as a wrapper around an existing class. This pattern creates a decorated class that wraps the original class and provides additional functionality while maintaining the integrity of the class's method signatures.
We demonstrate the usage of the decorator pattern through the following example. Among them, we will decorate a shape with a different color without changing the shape class
Model principle
- Component: abstract component
- ConcreteComponent: Concrete component
- Decorator: abstract decorator class
- ConcreteDecorator: Concrete decoration class
Case Analysis
We will create a Shape interface and an entity class that implements the Shape interface. Then we create an abstract decorator class ShapeDecorator that implements the Shape interface , and use the Shape object as its instance variable.
RedShapeDecorator is an entity class that implements ShapeDecorator .
DecoratorPatternDemo , our demo class uses RedShapeDecorator to decorate Shape objects.
pattern analysis
advantage
1. Hierarchical complex objects can be clearly defined, representing all or part of the object hierarchy, making it easier to add new components.
2. The client call is simple, and the client can use the combined structure or a single object consistently.
3. Define a class hierarchy including leaf objects and container objects. Leaf objects can be combined into more complex container objects, and this container object can be combined, so that recursively, a complex tree structure can be formed.
4. It is easier to add object components in the composition body, and the client does not have to change the original code because of adding new object components.
shortcoming
Make the design more abstract, if the business rules of the object are complex, it is very challenging to implement the composition pattern, and not all methods are associated with the leaf object subclass