1. Concept:
(In my opinion, the pattern is like a thought, under the guidance of this thought, the processing and integration of code and Structure!) It's all a routine! )
Decorative mode, also known as packaging (Wrapper) mode, is the ability to extend an object transparently to the client, which is an alternative to the inheritance relationship. Transparent to the client means that the interface is not changed.
2. Questions :
In the OO design and development process, you often encounter the following scenario: We need to add new responsibilities to the already designed classes, and typically we define a new class that inherits the custom class. Because the combination is better than inheritance (high complexity, deep inheritance depth, etc.),
Class Diagram :
3, how to achieve the decoration:
(1): Inherited form: (not recommended)
When we add new functionality to a class that has already been designed, you can create a new class, inherit the existing class, and add the new required functionality to the new subclass! But that's not good! Whenever a new feature occurs, you need to create a new inheriting subclass.
It's a bit of a hassle and it doesn't fit well with encapsulation and loose coupling!
Code Description:
1 /**2 * Assume that the classes that have been designed are as follows:3 */4 classOldclass {5 6 //function 17 Public voidmethod1 () {}8 9 //function 2Ten Public intmethod2 () {} One A}
Now you need to add a new feature: (Inherit decorative form)
1 /**2 * Inherited decorative forms:3 */4 classNewclassextendsoldclass{5 6 //the original function is inherited from7 8 //new Features9 Public voidmethod3 () {}Ten}
(2): Implement Interface form: (recommended)
Because Java is a single inheritance, many implementations, all do not recommend the use of inherited base class to implement the addition of new functions, implementation of the interface, you can add new functions on the basis of the original class, only the interface to write good correspondence to the new function, in the implementation can!
The benefits are also obvious, in accordance with the characteristics of loose coupling and have a strong class expansion.
Code Description:
/***/class 5 6 // function 1 7 public void8 9 // function 2public int method2 () {} 12}
Write an interface for a new feature:
1 /** 2 * New Function interface 3 */ 4 Public Interface newclassimp{56 // new Function abstract method declaration 7 Public void method3 (); 8 }
The original base class implements the new functional interface:
1/**2 * Class 3 with new features added*/4classOldclassImplementsnewclassimp{5 6//function 17 Public voidmethod1 () {}8 9//function 210 Public intmethod2 () {}1112//Implement new features13 Public voidmethod3 () {}14}
Java design pattern----Decorative Mode