Created
August 7, 2013 06:35
-
-
Save ErikZhou/6171746 to your computer and use it in GitHub Desktop.
Structural Patterns - Decorator C# demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
class MainApp | |
{ | |
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.Read(); | |
} | |
} | |
// "Component" | |
abstract class Component | |
{ | |
public abstract void Operation(); | |
} | |
// "ConcreteComponent" | |
class ConcreteComponent : Component | |
{ | |
public override void Operation() | |
{ | |
Console.WriteLine("ConcreteComponent.Operation()"); | |
} | |
} | |
// "Decorator" | |
abstract class Decorator : Component | |
{ | |
protected Component component; | |
public void SetComponent(Component component) | |
{ | |
this.component = component; | |
} | |
public override void Operation() | |
{ | |
if (component != null) | |
{ | |
component.Operation(); | |
} | |
} | |
} | |
// "ConcreteDecoratorA" | |
class ConcreteDecoratorA : Decorator | |
{ | |
private string addedState; | |
public override void Operation() | |
{ | |
base.Operation(); | |
addedState = "New State"; | |
Console.WriteLine("ConcreteDecoratorA.Operation()"); | |
} | |
} | |
// "ConcreteDecoratorB" | |
class ConcreteDecoratorB : Decorator | |
{ | |
public override void Operation() | |
{ | |
base.Operation(); | |
AddedBehavior(); | |
Console.WriteLine("ConcreteDecoratorB.Operation()"); | |
} | |
void AddedBehavior() | |
{ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment