您的位置:首页 > 其它

装饰模式 Decorator

2017-04-08 11:43 127 查看
装饰模式 Decorator:动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更灵活



上图中

ConcreteComponent:定义了一个具体的对象,也可以对这个对象添加一些职责

ConcreteDecorator:具体装饰类对象,起到给Component添加职责的功能

Decorator:装饰抽象类,继承Component,扩展Component功能,但对Component无需知道Decorator存在

代码实现C#

//Component类
abstract class Component
{

public abstract void Operation();
}

//ConcreteComponent类
class ConcreteComponent : Component
{

public override void Operation()
{
//具体操作
Console.WriteLine("具体操作");
}
}

abstract class Decorator : Component
{

protected Component component;

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

public override void Operation()
{//重写Operation(),实际执行Component的Operation()
if (component != null)
{
component.Operation();
}
}
}

class ConcreteDecoratorA : Decorator
{

private String addedState;//本类独有功能,区别ConcreteDecorator

public override void Operation()
{
base.Operation();//先运行原Component的Operation,在执行本类功能,如addedState,相当于对Component进行装饰
addedState = "New state";
Console.WriteLine("具体装饰对象A的操作");
}
}

class ConcreteDecoratorB : Decorator
{

public override void Operation()
{
base.Operation();//先运行原Component的Operation,在执行本类功能,
//如AddedBehavior(),相当于对Component进行装饰
AddedBehavior();
Console.WriteLine("具体装饰对象B的操作");
}

private void AddedBehavior()
{

}//本类独特方法,以区别ConcreteDecoratorA
}


//客户端代码
static void Main(string[] args)
{
ConcreteComponent c = new ConcreteComponent();
ConcreteDecoratorA d1 = new ConcreteDecoratorA();
ConcreteDecoratorB d2 = new ConcreteDecoratorB();

d1.SetComponent(c);//先用ConcreteComponent实例化对象c,然后用ConcreteComponentA的实例化对象d1包装c,
//再用ConcreteDecoratorB的对象包装d1,最终执行d2的Operation()
d2.SetComponent(d1);
d2.Operation();

Console.Read();
}


创建型模式,共五种:工厂方法模式、抽象工厂模式、单例模式、建造者模式、原型模式。

结构型模式,共七种:适配器模式、装饰器模式、代理模式、外观模式、桥接模式、组合模式、享元模式。

行为型模式,共十一种:策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: