• ไทย (ไทย)
    • English (United States)
    • العربية (مصر)
    • Deutsch (Deutschland)
    • Español (España, alfabetización internacional)
    • français (France)
    • हिंदी (भारत)
    • italiano (Italia)
    • 日本語 (日本)
    • 한국어 (대한민국)
    • Nederlands (Nederland)
    • polski (Polska)
    • русский (Россия)
    • Türkçe (Türkiye)
    • Tiếng Việt (Việt Nam)
    • 中文(中华人民共和国)
    • 中文(香港特別行政區)
  • เข้าสู่ระบบ
  • การลงทะเบียน
DotNetAge - Mvc & jQuery CMS
ซ่อน sidebar

Decorator


Definition



Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

UML class diagram





Participants



The classes and/or objects participating in this pattern are:
  • Component - defines the interface for objects that can have responsibilities added to them dynamically.
  • ConcreteComponent - defines an object to which additional responsibilities can be attached.
  • Decorator - maintains a reference to a Component object and defines an interface that conforms to Component's interface.
  • ConcreteDecorator - adds responsibilities to the component.

Sample code in C#




///
/// MainApp startup class for Structural
/// Decorator Design Pattern.
///
class MainApp
{
///
/// Entry point into console application.
///
static void Main()
{
// Create ConcreteComponent and two Decorators
ConcreteComponent c = new ConcreteComponent();
ConcreteDecoratorA d1 = new ConcreteDecoratorA();
ConcreteDecoratorB d2 = new ConcreteDecoratorB();


// Link decorators
d1.SetComponent(c);
d2.SetComponent(d1);

d2.Operation();

// Wait for user
Console.ReadKey();
}
}


///
/// The 'Component' abstract class
///
abstract class Component
{
public abstract void Operation();
}

///
/// The 'ConcreteComponent' class
///
class ConcreteComponent : Component
{
public override void Operation()
{
Console.WriteLine("ConcreteComponent.Operation()");
}
}

///
/// The 'Decorator' abstract class
///
abstract class Decorator : Component
{
protected Component component;

public void SetComponent(Component component)
{
this.component = component;
}

public override void Operation()
{
if (component != null)
{
component.Operation();
}
}
}

///
/// The 'ConcreteDecoratorA' class
///
class ConcreteDecoratorA : Decorator
{
public override void Operation()
{
base.Operation();
Console.WriteLine("ConcreteDecoratorA.Operation()");
}
}

///
/// The 'ConcreteDecoratorB' class
///
class ConcreteDecoratorB : Decorator
{
public override void Operation()
{
base.Operation();
AddedBehavior();
Console.WriteLine("ConcreteDecoratorB.Operation()");
}

void AddedBehavior()
{
}
}

 


    Average:
  • อ่าน
    (721)
  • Permalink
ใช้ร่วมกับ:

Tag cloud

Anything in here will be replaced on browsers that support the canvas element