C # Decorator Mode

Source: Internet
Author: User

Decorator mode

1. Overview:

Dynamically adding some additional responsibilities to an object, the adornment mode is more flexible than generating subclasses for added functionality.      

2. Principle:

Add a modified class to wrap the original class, wrapping it in general by using the original object as an argument to the constructor of the decorated class. The adornment class implements new functionality, but where new functionality is not required, it can invoke the methods in the original class directly, and the decorated class must have the same interface as the original class.       

3. Roles in the pattern

3.1: Abstract Build (Component): Defines an abstract interface to dynamically add responsibilities to these objects.

3.2: Concrete Build (Concretecomponent): Define a specific object, or you can add some responsibilities to the object.

3.3: Decoration Class (Decorator): Decorate abstract class, inherit component, extend the function of component class from outer class.

3.4: Concrete Decorator (Concretordecorator): Responsible for adding responsibilities to the construction object.

4. Pattern Interpretation:

5. Analysis of application Examples:

Problem: Equipped with a private soldier, without any equipment (core function) can use punching, equipped with rifles, can use rifles for shooting, equipped with heavy machine guns, can use heavy machine guns to shoot, equipped with a rocket launcher, you can use the rocket cylinder for air defense.

5.1 Definition of the equipment class:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacedecoration Mode {/// <summary>    ///Equipment class equivalent to component/// </summary>     Public Abstract classEquipment { Public Abstract voidAttack (); }}

5.2: Define a specific object and add some responsibilities to the object:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacedecoration Mode {/// <summary>    ///define a specific object and add some responsibilities to the object. /// </summary>    classsoldier:equipment {/// <summary>        ///without any weapon equipped with the core of the function/// </summary>         Public Override voidAttack () {Console.WriteLine ("to attack with a fist ."); }    }}

5.3: Define an abstract equipment decoration class:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacedecoration Mode {/// <summary>    ///Equipment Decoration Class (abstract class)/// </summary>     Public Abstract classequipdecorator:equipment {protectedequipment equipment; /// <summary>        ///Increase equipment Use this method to dynamically increase the equipment for soldiers/// </summary>        /// <param name= "Equipment" >Settings for Components</param>         Public voidsetcomponent (equipment equipment) { This. Equipment =equipment; }        /// <summary>        ///If you have the equipment, attack with the equipment ./// </summary>         Public Override voidAttack () {if(Equipment! =NULL) {equipment.attack (); }        }    }}

5.4: Additions to each subclass:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacedecoration Mode {/// <summary>    ///Rifle/// </summary>     Public classRifleequipment:equipdecorator { Public Override voidAttack () {Base.            Attack (); Console.WriteLine ("Rifle Shooter"); }    }}
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacedecoration Mode {/// <summary>    ///machine Guns/// </summary>     Public classMachinegunequipment:equipdecorator { Public Override voidAttack () {Base.            Attack (); Console.WriteLine ("Machine gun Shooting"); }    }}
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacedecoration Mode {/// <summary>    ///Rocket Shooter/// </summary>     Public classRocketgunequipment:equipdecorator { Public Override voidAttack () {Base.            Attack (); Console.WriteLine ("Rocket Shooter"); }    }}

5.5: Call to client code:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacedecoration Mode {classProgram {Static voidMain (string[] args) {            //Defining recruitsSoldier Soldier =NewSoldier (); //three kinds of equipmentRifleequipment rifleequipment =Newrifleequipment (); Machinegunequipment machinegunequipment=Newmachinegunequipment (); Rocketgunequipment rocketgunequipment=Newrocketgunequipment (); //give all three kinds of equipment to the recruits .rifleequipment.setcomponent (soldier);            Machinegunequipment.setcomponent (rifleequipment);            Rocketgunequipment.setcomponent (machinegunequipment); //In addition to the attack, the recruits can also use rifle machine gun rockets to finally execute the ROCKETGUNEQUIPMENT.ATTCCK ();Rocketgunequipment.attack ();        Console.readkey (); }    }}

5.6: as follows:

6: Summary of decorative patterns

Summary: Decorative mode is a way to add more versatility to existing features dynamically.

When new functionality is needed, new code is added to the old class, which usually decorates the core of the original class or the main function. But the problem with this approach is that they add new fields, new methods, or new logic to the main class, adding to the complexity of the main class. And these new things are just to meet the needs of specific behaviors that will be performed in certain circumstances. And the decorating mode offers a very good solution. It puts each function that is to be decorated in a separate class and lets the class wrap the object it wants to decorate, so that when you perform a special behavior, the client code can be packaged with a selective, sequential use of decorating functionality at run time.

The advantage of decorating mode is that the decoration function in the class is removed from the class so that the original class can be simplified.

So the best thing to do is to effectively separate the core functions of the class from the decorative functions, and to remove duplicate code from the related classes.

C # Decorator 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.