设计模式 -(5)装饰模式(结构型)

(Decorator)
  1. 装饰模式以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案。
  2. 装饰模式以对客户透明的方式动态地给一个对象附加上更多的责任,装饰者模式相比生成子类可以更灵活地增加功能。
  3. 装饰模式可以在不增加子类的情况下,将对象的功能加以扩展
  4. 装饰模式是把客户端的调用委派到被装饰类装饰模式的关键在于扩展完全透明的。
  5. 装饰模式是在不必改变原类文件使用继承的情况下,动态的扩展一个对象的功能。它是通过创建一个包装对象,也就是来包裹真实对象。

装饰模式的角色:

抽象构件角色(Component):给出一个抽象接口,以规范准备接收附加责任的对象。
具体构件角色(Concrete Component):定义一个将要接收附加责任的类
装饰角色(Decorator)持有一个构件(Component)对象的引用,并定义一个与抽象构件接口一致的接口。
具体装饰角色(Concrete Decorator):负责给构件兑现“贴上”附加的责任。

装饰模式的特点:
  1. 装饰对象和真实对象有相同的接口,这样客户端对象就可以以和真实对象相同的方式和装饰对象交互
  2. 装饰对象包含一个真实对象的引用
  3. 装饰对象接收所有来自客户端的请求。它把这些请求转发给真实的对象。
  4. 装饰对象可以转发这些请求以前或以后增加一些附加功能。这样就确保了在运行时,不用修改给定对象的接口就可以在外部增加附加的功能。在面向对象的设计中,通常是通过继承来实现对给定类的功能拓展。


时序图



IComponent.cs
    interface IComponent
    {
        void DoSomething();
    } 

ConcreteComponent.cs
    class ConcreteComponent : IComponent
    {
        public void DoSomething()
        {
            Console.WriteLine("功能A");
        }
    } 

Decretor.cs
    class Decretor : IComponent
    {
        private IComponent _component;

        public Decretor(IComponent Component)
        {
            this._component = Component;
        }

        public virtual void DoSomething()
        {
            this._component.DoSomething();
        }
    } 

ConcreteDecorator1.cs
    class ConcreteDecorator1 : Decretor
    {
        public ConcreteDecorator1(IComponent component):base(component){}

        public override void DoSomething()
        {
            base.DoSomething();
            this.DoAnotherThing();
        }
        private void DoAnotherThing()
        {
            Console.WriteLine("功能B");
        }
    } 

ConcreteDecorator2.cs
    class ConcreteDecorator2 : Decretor
    {
        public ConcreteDecorator2(IComponent component) : base(component) { }

        public override void DoSomething()
        {
            base.DoSomething();
            this.DoAnotherThing();
        }

        private void DoAnotherThing()
        {
            Console.WriteLine("功能C");
        }
    } 

Client.cs
    class Client
    {
        static void Main(string[] args)
        {
            Decretor decretor = new ConcreteDecorator1(new ConcreteDecorator2(new ConcreteComponent()));
            decretor.DoSomething();
            
            Console.Read();
        }
    } 


例子2:





posted @ 2016-09-23 15:50  【唐】三三  阅读(361)  评论(0编辑  收藏  举报