Decorator mode (Decorator pattern) C # version of

Source: Internet
Author: User

Still from Zhili https://www.cnblogs.com/zhili/p/DecoratorPattern.html

Thank you, hehe.

----------------------------------------------------Split Line--------------------------------------------------------

First, Introduction

In software development, we often want to add different functions to a class of objects, such as to add film, mobile phone pendant, mobile phone shell, etc., if the use of inheritance at this time to achieve, you need to define a myriad of classes, such as Stickerphone (film is mobile phone class), Accessoriesphone (Pendant phone Class) and so on, this will lead to the "sub-class explosion" problem, in order to solve this problem, we can use the decorator mode to dynamically add additional responsibilities to an object . Let's look at the decorator pattern below.

Ii. Detailed description of the decorator model2.1 Definitions

Decorator mode dynamically attaches more responsibility to an object in a transparent manner to the customer, and the decorator pattern adds more flexibility to the functionality than it is to generate subclasses.

2.2 Decorator Mode implementation

Here are examples of mobile phone and mobile phone accessories to demonstrate the implementation of the decorator pattern, the code is as follows:

///<summary>///Cell phone abstract class, which is the abstract component class in decorator mode///</summary>PublicAbstractClassPhone {PublicAbstractvoidPrint (); }///<summary>///Apple phones, which are decorated with specific component classes in the pattern///</summary>PublicClassApplephone:phone {///<summary>///overriding base class methods///</summary>PublicOverridevoidPrint () {Console.WriteLine ("Start executing specific objects--Apple phones"); } }///<summary>///Decorative abstract class, to let the decoration completely replace the abstract components, so must inherit from photo///</summary>PublicAbstractClassDecorator:phone {PrivatePhone phone;PublicDecorator (Phone p) {This.phone =P }PublicOverridevoidPrint () {if (Phone! =Null) {phone. Print (); } } }///<summary>///Foil, that is, the specific decorator///</summary>PublicClassSticker:decorator {PublicSticker (Phone p):Base(p) {}PublicOverridevoidPrint () {Base. Print ();//Add a new behaviorAddsticker (); }///<summary>///New ways of behaving///</summary>PublicvoidAddsticker () {Console.WriteLine ("Now the Apple phone has a foil"); } }///<summary>///Mobile phone Pendant///</summary>PublicClassAccessories:decorator {PublicAccessories (Phone P):Base(p) {}public override void Print () {base// add a new behavior  Addaccessories ( ); } ///<summary> ///< Span style= "COLOR: #008000" > new behavior method ///</summary> Span style= "COLOR: #0000ff" >public void Addaccessories () {Console.WriteLine ( " Now the iphone has a beautiful pendant.  ");}         

At this point the client invocation code is as follows:

ClassCustomer {Staticvoid Main (String[] args) {//I bought an apple mobile phone phone phoneNewApplephone ();//Now I want to film the Decorator Applephonewithsticker =NewSticker (phone);//Extended foil BehaviorApplephonewithsticker.print (); Console.WriteLine ("----------------------\ n");// Now I want to have a pendant Decorator applephonewithaccessories = new accessories (phone); // extended phone pendant behavior  Applephonewithaccessories.print (); Console.WriteLine ( "----------------------\n "); // Now I have the foil and the phone pendant. Sticker sticker = new sticker (phone); Accessories Applephonewithaccessoriesandsticker = new Accessories (sticker); Applephonewithaccessoriesandsticker.print (); Console.ReadLine (); } 

As can be seen from the client code above, the client can dynamically add mobile phone accessories to the phone, if you need to add a phone shell, this time only need to add an inherited decorator phone shell class, thus, the Decorator mode extensibility is also very good.

2.3 class diagram for decorator mode

After finishing the decorator pattern, let's look at the relationship between the classes in the decorator pattern implementation, see:

In decorator mode, the individual characters are:

    • Abstract component (Phone) role: An abstract interface is given to standardize the objects that are ready to accept additional responsibilities.
    • Concrete Component (Appphone) Role: Defines a class that will receive additional responsibilities.
    • Decoration (dicorator) Role: Holds an instance of a component (Component) object and defines an interface that is consistent with the abstract component interface.
    • Specific decorations (sticker and accessories) roles: Responsible for attaching additional responsibilities to the component objects.

third, the advantages and disadvantages of the decorator model

After reading the details of decorator mode, we continue to analyze its pros and cons.

Advantages:
    1. Decoration This mode and inheritance are intended to extend the functionality of objects, but decorator mode is more flexible than inheritance
    2. By using different decorative classes and permutations of these classes, designers can create combinations of many different behaviors.
    3. Decorator mode is well scalable

cons : Decorator mode causes many small objects to appear in the design, which can make the program more complex if used excessively. And more objects are going to make mistakes that are difficult, especially when these objects look alike.

Iv. use of the scene

Let's look at what the decorator pattern is used in, and the decorator mode should be used in the following cases:

    1. You need to extend the functionality of a class or add additional responsibilities to a class.
    2. You need to dynamically add functionality to an object that can be revoked dynamically.
    3. Need to increase the amount of functionality that arises from the combination of some basic functions
v.. The implementation of decorator pattern in net

There is also an implementation of the decorator pattern in the. NET class Library, which is System.IO.Stream, which looks at the Stream class structure:

, BufferedStream, CryptoStream and GZipStream are actually two concrete decorations, where the decorator pattern omits the abstract decorative character (Decorator). The following shows how the client dynamically adds functionality to the MemoryStream dynamically.

MemoryStream MemoryStream =New MemoryStream (NewByte[] {95,96,97,98,99}); // extended buffering feature BufferedStream Buffstream = new BufferedStream (MemoryStream); // add encrypted features CryptoStream CryptoStream = new CryptoStream (Memorystream,new aesmanaged ( ). CreateEncryptor (), cryptostreammode.write); // add compression function GZipStream GZipStream = new gzipstream (MemoryStream, compressionmode.compress,  true)                 
Vi. Summary

In this case, the decorator mode is finished, and the decorator pattern implements the ability to dynamically expand the object's functionality when it is run again, using object combinations rather than inheritance, and can extend multiple functions as needed to avoid the "poor flexibility" and "multi-subclass derivation problems" that are inherited by using inheritance alone. At the same time, it conforms well to the principle of object-oriented design, which is "preferential use of object combination rather than inheritance" and "open-closed".

Decorator mode (Decorator pattern) C # version of

Related Article

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.