设计模式三(装饰者模式)
1.妆饰者模式就是先定义一个抽象类或接口,然后用一个类去继承并实现它的方法,然后
另外一个类也去继承它,但是这个类除了去实现它的接口以外还有就是在它的内部有一个
父类类型的保护变量,并且为这个变量专门卡发了一个方法来设置这个变量,这样在实现
父类的接口方法时候就先判断这个变量存在不,如果存在就调用这个变量的方法,以后要进
行扩展的装饰类都继承这个类,在重写这个类的方法的时候都先调用base.方法,这样就能先
调用父类的方法,然后在调用子类的方法
优点:它把每个要装饰的功能放在单独的类中,并让这个类去包装它要装饰的对象。因此我们可以选择的,按顺序的使用它包装对象。(如加密等),它把类的核心职责和装饰功能分开。
2.图解

3.实例代码--来自大话设计模式
class Program
{
static void Main(string[] args)
{
ConcreteComponent c = new ConcreteComponent();
ConcreteDecoratorA d1 = new ConcreteDecoratorA();
ConcreteDecoratorB d2 = new ConcreteDecoratorB();
d1.SetComponent(c);
d2.SetComponent(d1);
d2.Operation();
Console.Read();
}
}
abstract class Component
{
public abstract void Operation();
}
class ConcreteComponent : Component
{
public override void Operation()
{
Console.WriteLine("具体对象的操作");
}
}
abstract class Decorator : Component
{
protected Component component;
public void SetComponent(Component component)
{
this.component = component;
}
public override void Operation()
{
if (component != null)
{
component.Operation();
}
}
}
class ConcreteDecoratorA : Decorator
{
private string addedState;//这个只是作一个比较区别于下面的ConcreteDecoratorB,没有具体含义
public override void Operation()
{
base.Operation();
addedState = "New State";
Console.WriteLine("具体装饰对象A的操作");
}
}
class ConcreteDecoratorB : Decorator
{
public override void Operation()
{
base.Operation();
AddedBehavior();
Console.WriteLine("具体装饰对象B的操作");
}
private void AddedBehavior()//这个只是作一个比较区别于上面的ConcreteDecoratorA,没有具体含义
{
}
}

浙公网安备 33010602011771号