First, let's take a look at the example of reading a book! Example of people wearing clothes!
A class chart is a simple class structure.
CodeAs follows:
# Include <iostream> using namespace STD; class person {PRIVATE: string name; public: Person (string name) {This-> name = Name;} void weartshirts () {cout <"big t-shirt" <Endl;} void wearbigtrouser () {cout <"Cross pants" <Endl;} void wearsneakers () {cout <"Broken sneakers" <Endl;} void wearsuit () {cout <"Suit" <Endl;} void weartie () {cout <"Tie" <Endl;} void wearleathershoes () {cout <"Shoes" <Endl;} void show () {cout <"Dress Up" <name. c_str () <Endl ;}; int main (INT argc, char * argv []) {person * P = new person (" "); cout <"first dress up" <Endl; P-> wearleathershoes (); P-> wearsuit (); P-> wearbigtrouser (); P-> show (); cout <"second dress up" <Endl; P-> wearleathershoes (); P-> weartshirts (); P-> wearsneakers (); P-> show (); return 0 ;}
If you want to add a new dress, you need to modify the structure of the person class, which violatesPrinciple of opening/closing
The changes are abstracted first, so the class graph structure is as follows:
Corresponding to the above implementationProgramIt seems to be a little more convenient, but what if I continue to increase the demand? There will be many sub-classes.
This leads to the decoration mode.
The decoration mode dynamically adds attributes and responsibilities to objects.
The class structure is as follows:
Componment is an object interface defined to dynamically add roles to these objects.
Concertcomponent is the object to be decorated, that is, the original object.
Dectorator is an abstract decorative class
Concertdectoratora and concertdectoratorb are decoration objects.
Let's look at the original class chart modification as follows:
In this way, the dynamic loading of human objects can be realized. However, this example is not very good and does not list the essence of the decoration mode.