What does it mean to decorate a class or parameter?

What does it mean to decorate or add an attribute to a class or parameter?
What is the purpose and when will I do it?

Links to resources and direct answers are welcome.

Thank you

+11
source share
3 answers

When you add a decorator in C #, it is like adding a property to a class / method. An attribute will be attached to it.

If you write unit test, you will come across a simple TestMethod decorator, for example:

 [TestMethod] public void TestMethod1() { } 

The framework will use decorators to test testing methods in the test suite.

You can check the attribute here

There is another nice article about writing custom attributes.

Decorators are not limited to the shape of decorators []. There is also a design template for this that others have already mentioned.

+5
source

The decorator was one of the first 26 patterns described in The Gangs of Four, Design Templates . They describe it well here .

Summary:

Decorator: Add extra functionality to the class at run time, where subclassing will exponentially grow new classes

Templates are language independent. These are descriptions of solutions to common problems in object-oriented programming. It is perhaps even preferable to discuss them without reference to a specific language. The examples in the original book were written in C ++ and Smalltalk. Neither Java nor C # existed when the book was first published in 1995.

+4
source

Decorating a class means adding functionality to an existing class. For example, you have a SingingPerson class that has a talent for singing.

 public class SingingPerson { public string Talent = "I can sing"; public string DoTalent() { return Talent; } } 

You later decided that the SingingPerson class should also dance, but did not want to modify the existing class structure. What you do is decorate the SingingPerson class by creating another class that contains the added functionality. This new class that you create accepts a SinginPerson object.

 public class SingingAndDancingPerson { SingingPerson person; public string Talent { get; set; } public SingingAndDancingPerson(SingingPerson person) { this.person = person; } public string DoTalent() { this.Talent = person.Talent; this.Talent += " and dance"; return this.Talent; } } 

When trying to instantiate these classes, the output will be as follows:

  SingingPerson person1 = new SingingPerson(); Console.WriteLine("Person 1: " + person1.DoTalent()); SingingAndDancingPerson person2 = new SingingAndDancingPerson(person1); Console.WriteLine("Person 2: " + person2.DoTalent()); Console.ReadLine(); 
+1
source

All Articles