导航

学完模式判若两人——装饰模式

Posted on 2010-04-22 11:36  敬云  阅读(238)  评论(0)    收藏  举报

装饰模式:动态地为一个对象增加一些额外的职责。

就增加功能来说,装饰模式比生成子类更加灵活

下图为装饰模式的结构图:

Component: 定义了一个对象的接口,使得可以为这些对象动态的增添一些额外的功能。

ConcreteComponent: 核心功能类,描述对象的具体功能。比如手机类的核心功能——通话功能。

Decorator: 装饰抽象类,继承自Component,从而可以扩展Component的功能。

ConcreteComponentA: 具体装饰类A,可以为Component扩展一些功能,比如手机类的扩展功能——拍摄功能。

ConcreteComponentB: 具体装饰类B,作用同上。

 

定义代码如下:

 

代码
    abstract class Component
    {
        
private string _functions;
        
public string Functions
        {
            
get { return this._functions; }
            
set { this._functions = value; }
        }
        
public abstract string ShowFunctions();
    }
    
class ConcreteComponent : Component
    {
        
public ConcreteComponent()
        {
            
this.Functions += "手机核心功能;";
        }
        
public override string ShowFunctions()
        {
            
return this.Functions;
        }
    }
    
class Decorator : Component
    {
        
protected Component component;

        
public void SetComponent(Component component)
        {
            
this.component = component;
        }
        
public override string ShowFunctions()
        {
            
if (this.component != null)
            {
                
return this.component.ShowFunctions();
            }
            
else return "无功能";
        }
    }
    
class ConcreteDecoratorA : Decorator
    {
        
public override string ShowFunctions()
        {
            
this.component.Functions += "附加功能A";
            
return base.ShowFunctions();
        }
    }
    
class ConcreteDecoratorB : Decorator
    {
        
public override string ShowFunctions()
        {
            
this.component.Functions += "附加功能B";
            
return base.ShowFunctions();
        }
    }

 

 

在控制台运行代码:

 

代码
        static void Main(string[] args)
        {
            
//手机类 具有基本功能
            ConcreteComponent phone = new ConcreteComponent();
            
//展示手机现在功能
            Console.WriteLine(phone.ShowFunctions());
            
//修饰类A 具有修饰功能A 使之修饰手机phone
            ConcreteDecoratorA decoratorA = new ConcreteDecoratorA();
            decoratorA.SetComponent(phone);
            
//展示手机现在功能
            Console.WriteLine(decoratorA.ShowFunctions());
            
//修饰类B 具有修饰功能B 使之修饰手机phone
            ConcreteDecoratorB decoratorB = new ConcreteDecoratorB();
            decoratorB.SetComponent(phone);
            
//展示手机现在功能
            Console.WriteLine(decoratorB.ShowFunctions());

            Console.ReadKey();
        }

 

运行结果:

 

在结果上可以看出,Component被子类一层一层的包装了,这就是装饰模式。

换个例子可能更直观,我们把Component类看成人,ConcreteComponentA,ConcreteComponentB 看成不同的衣服,比如内衣,外套,鞋子等。

这样我们可以任意搭配自己的服装,得到想要的结果。

 

实际上装饰模式是为了为已有模式动态添加更多功能的方式。

装饰模式最大的好处在于把类中用于修饰的代码移除,而只剩下类最核心的功能,这样简化了原来的类。

在扩展修饰功能时也更方便直观。