Decorator Pattern allows you to add new features to an existing object without changing its structure. This type of design pattern is a structured pattern that is a wrapper around an existing class.
This pattern creates a decorating class that wraps the original class and provides additional functionality while maintaining the integrity of the class method signature.
We use the following example to demonstrate the use of decorator mode. Among them, we will decorate a shape with different colors without changing the shape class.
Intent: Dynamically add some additional responsibilities to an object. In terms of adding functionality, the decorator mode is more flexible than generating subclasses.
Main solution: In general, we often use inheritance to extend a class. Since inheritance introduces static features into classes, and as the extended functionality increases, the subclasses will swell.
When to use: Extend the class if you don't want to add a lot of subclasses.
How to solve: Divide specific functional responsibilities and inherit the decorator mode.
Key Code: 1, the Component class acts as an abstract role and should not be implemented. 2, modify the class reference and inherit the Component class, the concrete extension class overrides the parent class method.
Application example: 1. Sun Wukong has 72 changes. When he became a "temple", he was still a monkey at all, but he also had the function of a temple. 2. No matter whether a picture has a picture frame or not, it can be hung on the wall, but usually there is a picture frame, and actually the picture frame is hung on the wall. Before hanging on the wall, the painting can be covered with glass and placed in the frame; at this time, the painting, the glass and the frame form an object.
Advantages: Decorating and decorating classes can be developed independently and not coupled to each other. Decorating patterns are an alternative to inheritance, and decorating patterns can dynamically extend the functionality of an implementation class.
Disadvantages: Multi-layer decoration is more complicated.
Usage scenarios: 1. Extend the functionality of a class. 2. Dynamically add functions and dynamically cancel.
Note: can be used instead of inheritance.
We will create an Shape interface and an entity class that implements the Shape interface. Then we create an abstract decoration class ShapeDecorator that implements the Shape interface and takes the Shape object as its instance variable.
RedShapeDecorator is an entity class that implements ShapeDecorator.
DecoratorPatternDemo, our demo class uses RedShapeDecorator to decorate the Shape object.
Create an interface:
Create an entity class that implements the interface.