装饰模式
2020-12-26 08:51:56 2 举报
装饰器模式
作者其他创作
大纲/内容
public abstract class Component { public abstract void Operation(); }
-component
ConcreteDecoratorA
-addedState:String
+ operation()
ConcreteComponent
public abstract class Decorator : Component { protected Component component; public void SetComponent(Component component) { this.component = component; } public override void Operation() { if (component != null) { component.Operation(); } } }
ConcreteDecoratorB
+ operation()-addedBehavor()
public class ConcreteDecoratorA : Decorator { private string addedState; public override void Operation() { base.Operation(); addedState = \"A New State\"; Console.WriteLine($\"具体装饰对象A的操作:{addedState}\"); } }
public class ConcreteComponent : Component { public override void Operation() { Console.WriteLine(\"具体对象的操作\"); } }
Decorator,装饰抽象类,继承了Component,从外类来扩展Component的功能,但对Component来说,是无需知道Decorator的功能的
Component定义一个对象接口,可以给这些对象动态添加职责
ConcreteComponent定义了一个具体对象,也可以给这个对象添加一些职责
Component
ConcreteDecorator是具体的装饰对象,起到给Decorator添加职责的功能
Decorator
//装饰模式 ConcreteComponent concreteComponent = new ConcreteComponent(); ConcreteDecoratorA concreteDecoratorA = new ConcreteDecoratorA(); ConcreteDecoratorB concreteDecoratorB = new ConcreteDecoratorB(); concreteDecoratorA.SetComponent(concreteComponent); concreteDecoratorB.SetComponent(concreteDecoratorA); concreteDecoratorB.Operation();
public class ConcreteDecoratorB : Decorator { public override void Operation() { base.Operation(); AddedBehavoior(); Console.WriteLine(\"具体装饰对象B的操作\"); } private void AddedBehavoior() { Console.WriteLine(\"B的方法\"); } }
0 条评论
下一页