标签:style blog http color io strong 2014 div sp
1、装饰者模式简介
意图:
适用性:
2、生活实例
3、装饰者模式结构
4、示意代码
// "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() { } }
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(); Console.Read(); }
}
4、总结
特点:
适用场景:
标签:style blog http color io strong 2014 div sp
原文地址:http://www.cnblogs.com/tianboblog/p/3921234.html