Design Mode learning-daily note (9. decorating Mode)

Source: Internet
Author: User

Decoration Mode

A. Definition:

Dynamically add some responsibilities to an object. The modifier mode is more flexible than the subclass generation function.

B. Definition Analysis:

"DynamicallyAdd some responsibilities to an object. The modifier mode is more flexible than the subclass generation function. "We know that the responsibility of an object is defined in the class, and the class method determines the responsibility of the object.

"Dynamically add some responsibilities to an object. The modifier mode is more flexible than the subclass generation function. "The decorator mode aims to dynamically add roles to objects without modifying classes.

"Dynamically add some responsibilities to an object.The modifier mode is more flexible than the subclass generation function."The modifier does not modify the class, But dynamically adds the object, of course, flexible.

C. Question:

(1) how to implement it?

Suppose there are classes A and Suba, and Suba inherits from a.a. There is an interface dress that indicates wearing clothes.

 1   Class A
2 {
3 Virtual Void Dress ( Void ) = 0 ;
4 };
5 Class Suba: Public A
6 {
7 Void Dress ( Void )
8 {
9 // Wear a T-shirt.
10 }
11 };

However, we suddenly want to extend the dress interface, but do not want to change a and Suba. At this time, we use the decoration mode:

ClassDecoratorhat:PublicA
{
A * m_p;
Decoratorhat (A * P)
: ()
{
M_p = P;
}
VoidDress (Void)
{
//Hats
M_p-> dress ();
}
};
ClassDecoratorglass:PublicA
{
A * m_p;
Decoratorglass (A * P)
: ()
{
M_p = P;
}
VoidDress (Void)
{
//Wear glasses
M_p-> dress ();
}
};

Decoratorhat and decoratorglass are the decorators. They can be used as follows:

A * P = NULL;
P =NewDecoratorhat (NewDecoratorglass (NewSuba ));
P-> dress ();

At this time, Suba will be decorated.

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.