Design Mode (3)-dress up your class (decoration Mode)

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.