设计模式学习之装饰者模式(Decorator,结构型模式)(16)

参考地址:http://www.cnblogs.com/zhili/p/DecoratorPattern.html

一、定义:
装饰者模式以对客户透明的方式动态地给一个对象附加上更多的责任,装饰者模式相比生成子类可以更灵活地增加功能。 

二、装饰者模式实现
在软件开发中,我们往往会想要给某一类对象增加不同的功能。比如要给汽车增加ESP、天窗或者定速巡航。如果利用继承来实现,就需要定义无数的类,Car,ESPCar,CCSCar,SunRoofCar,ESPCCSCar……很容易就导致“子类爆炸”问题。
上述“子类爆炸”问题的根源在于该解决方案利用继承来扩展功能,缺乏灵活性。

 public class Car
    {
        public virtual void Description()
        {
            Console.WriteLine("Basic Car");
        }
    }

    /// <summary>
    /// ESP装饰者
    /// </summary>
    public class ESPDecorator : Car
    {
        private Car _car;

        public ESPDecorator(Car car)
        {
            _car = car;
        }

        public override void Description()
        {
            _car.Description();
            Console.WriteLine("Add ESP");
        }
    }

    /// <summary>
    /// 定速巡航装饰者
    /// </summary>
    public class CCSDecorator : Car
    {
        private Car _car;

        public CCSDecorator(Car car)
        {
            _car = car;
        }

        public override void Description()
        {
            _car.Description();
            Console.WriteLine("Add CCS");
        }
    }

    /// <summary>
    /// 天窗装饰者
    /// </summary>
    public class SunRoofDecorator : Car
    {
        private Car _car;

        public SunRoofDecorator(Car car)
        {
            _car = car;
        }

        public override void Description()
        {
            _car.Description();
            Console.WriteLine("Add SunRoof");
        }
    }


    internal class Client
    {
        private static void Main(string[] args)
        {


            Car car = new ESPDecorator(new CCSDecorator(new SunRoofDecorator(new Car())));
            car.Description();
            Console.ReadKey();
        }
    }

三、装饰者模式的优缺点
看完装饰者模式的详细介绍之后,我们继续分析下它的优缺点。

优点:
装饰这模式和继承的目的都是扩展对象的功能,但装饰者模式比继承更灵活
通过使用不同的具体装饰类以及这些类的排列组合,设计师可以创造出很多不同行为的组合
装饰者模式有很好地可扩展性
缺点:装饰者模式会导致设计中出现许多小对象,如果过度使用,会让程序变的更复杂。并且更多的对象会是的差错变得困难,特别是这些对象看上去都很像。

四、使用场景
下面让我们看看装饰者模式具体在哪些情况下使用,在以下情况下应当使用装饰者模式:

需要扩展一个类的功能或给一个类增加附加责任。
需要动态地给一个对象增加功能,这些功能可以再动态地撤销。
需要增加由一些基本功能的排列组合而产生的非常大量的功能

五、.NET中装饰者模式的实现
在.NET 类库中也有装饰者模式的实现,该类就是System.IO.Stream,下面看看Stream类结构:

上图中,BufferedStream、CryptoStream和GZipStream其实就是两个具体装饰类,这里的装饰者模式省略了抽象装饰角色(Decorator)。下面演示下客户端如何动态地为MemoryStream动态增加功能的。

MemoryStream memoryStream = new MemoryStream(new byte[] {95,96,97,98,99});

            // 扩展缓冲的功能
            BufferedStream buffStream = new BufferedStream(memoryStream);

            // 添加加密的功能
            CryptoStream cryptoStream = new CryptoStream(memoryStream,new AesManaged().CreateEncryptor(),CryptoStreamMode.Write);
            // 添加压缩功能
            GZipStream gzipStream = new GZipStream(memoryStream, CompressionMode.Compress, true);

六、总结
到这里,装饰者模式的介绍就结束了,装饰者模式采用对象组合而非继承的方式实现了再运行时动态地扩展对象功能的能力,而且可以根据需要扩展多个功能,避免了单独使用继承带来的 ”灵活性差“和”多子类衍生问题“。同时它很好地符合面向对象设计原则中 ”优先使用对象组合而非继承“和”开放-封闭“原则。

posted @ 2014-10-11 13:54  学亮  阅读(189)  评论(0编辑  收藏  举报