C # design Pattern eight decorative mode (Decorator pattern) "Structural type"

Source: Internet
Author: User
Tags what interface

Original: C # design pattern of eight decorative mode (Decorator pattern) "Structural type"

First, Introduction

Today we are going to talk about the third mode of the "structural" design pattern, which is "decoration mode", English name: Decorator pattern. The first time I saw this name came to mind is another word "decoration", I said I say to the "decoration" understanding it, we must see clearly, is "decoration", not "decoration". We grow up, to get married, to get married involves to buy a house, buy the fine decoration or simple decoration can live, temporarily do not talk. Let's talk about what we bought is a rough room. If I want the interior of the house is marble-style, we just on the basis of the rough room with marble-style materials to decorate it, of course, we can not be a decoration style, the newly-built house has been demolished in the new. The house is well renovated, we live in, very happy. After a while, we found our house in the winter is cold, so I would like to add warmth to our house function, decoration of the house we can continue to live, we just add a layer of protection outside the House can be. After a while, there were always strangers, so we wanted to make the house safer, so we added security cameras to the outer walls and roofs, and the doors and windows added safety systems. As time goes by, we may increase the corresponding function according to our demand, during which our house can be used normally, plus what facilities will have the corresponding function. In this respect, "decoration" and "decoration" have a similar concept, then let us look at the decorative pattern is what it is!

Second, the decoration mode of the detailed introduction

2.1. Motive (motivate)

In the process of house decoration, various functions can be combined to increase the function of the house. Similarly, if we were to add functionality to a type or object in a software system, if we were to write the code using the "Inherit" scheme, there would be a case of sub-class spikes. For example: Imarblestyle is a marble-style function, ikeepwarm is an interface definition of insulation, ihousesecurity is a secure interface of the house, on three interfaces, house is our home, our house what function to achieve what interface, If the house wants a composite function, the different combinations of interfaces have different results, which leads to the expansion of our subclass, and if we need to increase the function, the subclass will grow exponentially. The root of the problem is that we "over-use inheritance to extend the functionality of an object," because of the static traits introduced into the type (the so-called static trait, that is, if you want a function, we must define the class at compile time, which is also the feature of the strongly typed language. Static refers to what is to be determined at compile time, which is what is determined at runtime, which makes this extension inflexible, and as the number of subclasses increases (the expansion function increases), the combination of each seed class (the combination of extended functions) causes more subclasses to swell (multiple inheritance). How can the extension of object functionality be implemented dynamically (that is, runtime) as needed? At the same time, avoid the problem of sub-class expansion caused by the increase of expansion function. So that the impact of any "functional expansion change" is reduced to a minimum?

2.2. Intention (Intent)

Add some additional responsibilities to an object dynamically.         In terms of increased functionality, the decorator mode is more flexible than generating subclasses. --"Design pattern" GoF

2.3. structure diagram (Structure)



2.4, the composition of the model

The various roles in the adornment mode are:

   (1), abstract component Role (Component): An abstract interface is given to standardize the preparation of objects that receive additional responsibilities.

   (2), specific component roles (concrete Component): Defines a class that will receive additional responsibilities.

   (3), decorative characters (Decorator): Holds an instance of a component (Component) object and implements an interface that is consistent with the abstract component interface.

   (4), the specific decorative role (concrete Decorator):Responsible for adding additional responsibilities to the component objects.

2.5, the specific code implementation of the decoration mode

Just start a look at this "decorative mode" is a bit less good understanding, since this model is object-oriented design pattern, that in real life there must be examples and its corresponding, in fact, this example is also a lot of people to dig it well, can also improve our understanding of object-oriented. I'm going to go get the house covered.

1 namespacethe implementation of decoration mode2 {3     /// <summary>4     ///the abstract class is the definition of the House abstract interface, the type is equivalent to the component type, is the dumpling stuffing, need to decorate, need to wrap5     /// </summary>6      Public Abstract class House7     {8         //How to decorate a house-this operation is equivalent to the operation method of the component type9          Public Abstract voidrenovation ();Ten     } One  A     /// <summary> -     ///the abstract class is the definition of the decorative interface, which is equivalent to the decorator type, and if you need specific functionality, you can subclass the type -     /// </summary> the      Public Abstract classDecorationstrategy:house//The key point of the second, the embodiment of the relationship is is-a, with this relationship, the decoration of the class can continue to decorate the -     { -        //The decorator type is referenced by a combination, and the type implements a specific function increase -         //This is one of the key points, including the relationship, embodied as Has-a +         protectedHouse _house; -  +         //through the constructor injection, initialize the platform implementation A         protectedDecorationstrategy ( House House) at         { -             This. _house=House ; -         } -  -        //This method is equivalent to the operation method of the decorator type. -         Public Override voidrenovation () in        { -            if( This. _house!=NULL) to             { +                  This. _house. Renovation (); -             } the         } *     } $  Panax Notoginseng     /// <summary> -     ///Patrickliu House, I want to do the house according to my request, the equivalent of concretecomponent type, this is our specific dumpling stuffing, I personally prefer leek stuffing the     /// </summary> +      Public Sealed classPatrickliuhouse:house A     { the          Public Override voidrenovation () +         { -Console.WriteLine ("RenovatedPatrickliu's house."); $         } $     } -   -  the    /// <summary> -     ///Security-enabled devices that provide monitoring and alerting capabilities, equivalent to Concretedecoratora typesWuyi     /// </summary> the      Public Sealed classHousesecuritydecorator:decorationstrategy -     { Wu          PublicHousesecuritydecorator (House House):Base(House) {} -  About          Public Override voidrenovation () $         { -             Base. Renovation (); -Console.WriteLine ("Increased security system"); -         } A     } +   the     /// <summary> -     ///material with insulation interface, provides insulation function, equivalent to Concretedecoratorb type $     /// </summary> the      Public Sealed classKeepwarmdecorator:decorationstrategy the     { the          PublicKeepwarmdecorator (House House):Base(House) {} the  -          Public Override voidrenovation () in         { the             Base. Renovation (); theConsole.WriteLine ("increase the function of heat preservation"); About         } the     } the  the     Public class Program +    { -       Static voidMain () the       {Bayi          //This is our dumpling stuffing, the house that needs decorating theHouse myselfhouse=Newpatrickliuhouse (); the  -Decorationstrategy securityhouse=NewHousesecuritydecorator (myselfhouse); - securityhouse.renovation (); the          //The House has a security system. the  the          //if I had to keep the security system warm, I'd go ahead and decorate . theDecorationstrategy securityandwarmhouse=NewHousesecuritydecorator (securityhouse); - Securityandwarmhouse. Renovation (); the       } the    } the}


Write a lot of notes, we have a good experience, there are two key points, carefully grasp.

Three, the implementation of decorative mode points:

1, through the use of combination, rather than the method of inheritance, the decorator model realizes inrun-time dynamicThe ability to extend object functionality, and can extend multiple functions as needed. Avoids the "poor flexibility" and "multi-subclass derivation problems" that are created by using inheritance alone.

2, Component class in the Decorator mode as the role of abstract interface, should not be to achieve specific behavior. And the decorator class should be transparent to the component class-in other words the component class does not need to know the decorator class, and the decorator class extends the functionality of the component class from the outside.

3. The Decorator class behaves as an inheritance of is-a component on the interface, that is, the decorator class inherits the interface that the component class has. But in the implementation of the HAS-A component of the composition of the relationship, that is, decorator class and use another component class. We can "decorate" a component object with one or more decorator objects, and the decorated object is still a Component object.

4, Decorator mode is not to solve the problem of "multiple inheritance of multi-sub-class derivation", the main point of application of decorator mode is to solve "the expansion function of principal class in multiple directions"-the Meaning of "decoration".

3.1 ", the advantages of decorative mode:

(1), decoupling the abstract interface from its implementation.

(2), abstraction and implementation can be independently extended, will not affect the other side.

(3), to achieve the details of the customer transparency, to be used to hide the specific implementation details.

3.2 ", the disadvantages of decoration mode:

(1), increase the complexity of the system

3.3 ", the bridging mode should be used in the following cases:

(1), if a system needs to add more flexibility between the component's abstract role and the materialized role, avoid establishing a static connection between the two levels.

(2), design requires that any changes to the role of the implementation should not affect the client, or the change in the implementation of the role of the client is completely transparent.

(3), graphics and windowing systems that need to span multiple platforms.

(4), a class has two independently changing dimensions, and two dimensions need to be expanded.

Iv. implementation of decorative patterns in. NET

In the NET Framework, there is one type that obviously uses the "adornment mode", which is the stream. The stream type is an abstract interface, which in the System.IO namespace is actually component. FileStream, NetworkStream, MemoryStream are all entity class concretecomponent. The BufferedStream and CryptoStream on the right are decorative objects, all of which inherit the stream interface.


Stream is equivalent to component, defining the object of adornment, FileStream is to decorate object, BufferedStream is adornment object. Let's take a look at the definition of BufferedStream, partially defined.

 1  public  sealed  class   Bufferedstream:stream  2  { 3  private  const  int  _defaultbuffersize = 4096  ;  4  5  private  Stream _stream; 

The structure is very simple, compare the structure of the chart see, there is nothing to say.

V. Summary

Today's article is written here, summed up my views on this model, this pattern is a bit like dumplings, concretecomponent is actually dumplings, decorator like dumplings, the skin is the same as the skin, skin and skin can also be nested, Of course, the dumplings in our life are only one layer. In fact, the mobile phone is also a good example of the use of decorative mode, our phone is just to answer the phone, and then can send text messages and MMS, I decorate one can take pictures. We now have a rich mobile phone, and the results are similar to the decorations. Along with the social progress, the technology development, the modular handset also appeared, its design principle also and "the adornment pattern" is closer. Not only mobile phones, but also many other household appliances around us have similar development experience, we try to find the truth in life, and then in the software environment slowly realized it.

C # design Pattern eight decorative mode (Decorator pattern) "Structural type"

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.