装饰模式是为已有的功能动态的添加更多功能的一种方式。当系统需要新功能的时候,一般就是想旧的类
中添加新的代码,这些新的代码通常装饰了原有类的核心职责或主要行为,但是在主类中添加新的字段,
新的方法,新的逻辑,会增加主类的复杂度。而这些新加入的东西仅仅是为了满足一些只在某些特定情况
下才会执行的特殊行为的需要。而装饰模式提供了解决方案,它把要装饰的功能放在单独的类中,并让这
个类包含它所要装饰的对象。优点:把类中的“装饰”功能从类中搬移出去,这样可以简化原有的类,因
此类的核心职责和装饰功能却分开了,而且可以去除相关类中重复的装饰逻辑。装饰模式属于结构型模式!
namespace Decorator
{
class Component //基本对象类,其中含有一些基本的功能
{
protected string _name;
public Component(string name)
{
this._name = name;
}
public void Operation()
{
//穿内衣
Console.WriteLine("my name is " + _name + "我已经穿上内衣");
}
}
class DecoratorA //装饰类A
{
public Component _component;
public DecoratorA(Component component)
{
this._component = component;
}
public void OperationA()
{
//对_Component进行装饰
Console.WriteLine("具体装饰对象A的操作");
}
}
class DecoratorB //装饰类B
{
public Component _component;
public DecoratorB(Component component)
{
this._component = component;
}
public void OperationB()
{
//对_Component进行装饰
Console.WriteLine("具体装饰对象B的操作");
}
}
class Client
{
static void Main()
{
Component c = new Component("mimi"); //产生对象
c.Operation(); //操作c的功能函数
DecoratorA d1 = new DecoratorA(c); ------分别调用A和B功能区“修饰”c
DecoratorB d2 = new DecoratorB(c);
d1.OperationA();
d2.OperationB();
Console.ReadKey();
}
}
}
可见策略模式是对主类的功能的分担,可以使主类更专注与一些核心功能,而“装饰”类继承主类可以灵活的为主类增加功能,而不必修改主类。这也符合开闭原则!