设计模式之装饰模式

来源:互联网 发布:淘宝的销量多久清零 编辑:程序博客网 时间:2024/06/06 05:01

     学习了设计模式中的装饰模式,首先它的概念:

为已有功能动态地添加更多功能的一种方式。也就是当系统仅仅是为了满足一些只在某种特定情况下才会执行的特殊行为,需要新的功能的时候,向旧的类中添加新的代码。装饰模式把要装饰的功能放在单独的类中,并让这个类包装它要装饰的对象。当需要执行特殊行为时,客户代码就可以在运行时根据需要有选择的按顺序的使用装饰功能包装对象了。即可以动态的添加新的功能。下面是结构图:


结合实际举个例子:我们平时吃的面条,需要往里面放入调味品,假如调味品为糖和盐,我们需要按照顺序分别放入糖和盐,那么调味品就是Decorator类,糖和盐分别为ConcreteDecoratorA和ConcreteDecoratorB。具体代码如下:

先定义一个meal类:

class Meal    {        public Meal()        { }        private string name;        public Meal(string name)        {            this.name = name;        }        public virtual void Add()        {            Console.WriteLine("添加到{0}中", name);        }    }
condiment(Decorator类)类继承于meal类:

 class Condiment : Meal    {        protected Meal component;        public void Decorate(Meal component)        {            this.component = component;        }        public override void Add()        {            if (component != null)            {                component.Add();            }        }    }
具体的sugar类和salt类(ConcreteDecorator类):

class Sugar : Condiment    {        public override void Add()        {            Console.Write("糖");            base.Add();        }    }    class Salt : Condiment    {        public override void Add()        {            Console.Write("盐");            base.Add();        }    }
客户端代码:

 <pre name="code" class="csharp"> static void Main(string[] args)        {            Meal noodle = new Meal("面条");            //装饰的过程            Console.WriteLine("\n第一种调味品:");            Sugar tang = new Sugar();            tang.Decorate(noodle);            tang.Add();                        Console.WriteLine("\n第二种调味品:");            Salt yan = new Salt();            yan.Decorate(noodle);            yan.Add();                       Console.Read();        }


这样运行的结果就是:



总结:decorator是动态地添加更多功能的一种方式,把要装饰的功能单独放在一个类中,把类的核心职责和装饰功能区分开,去除相关类中的重复装饰逻辑。



0 0
原创粉丝点击