结构型模式之装饰模式(Decorator)

来源:互联网 发布:苹果内购验证 java 编辑:程序博客网 时间:2024/05/29 11:44

              结构型模式的特点就是从程序的结构上解决模块之间的耦合问题。其中结构型模式包括:适配器模式、装饰模式、桥接模式、组合模式、享元模式、代理模式、外观模式。这里,我们重点说一下装饰模式。

  

引起:

    代码:

{    class Program    {        static void Main(string[] args)        {            Person xc = new Person("小菜");            Console.WriteLine("第一种装扮");            Finery dtx = new TShirts();            Finery kk = new BigTrouser();            dtx.Show();            kk.Show();            xc.Show();           Console.Read();        }    }    class Person    {        private string name;        public Person(string name)        {            this.name = name;        }        public void Show()        {            Console.WriteLine("装扮的{0}", name);        }        }    abstract class Finery    {        public abstract void Show();    }    class TShirts : Finery    {        public override void Show()        {            Console.Write("体恤");        }    }    class BigTrouser : Finery    {        public override void Show()        {            Console.Write("垮裤");        }        }}

       结果:  

                                           

       问题:


        虽然做到了服饰类和人类的分离,但是还存在没有把所需的功能按照正确的顺序串联起来而进行控制。

定义:


      装饰模式,动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。


结构图:

                       

 代码:

  class Program    {        static void Main(string[] args)        {            Person xc = new Person("小菜");            Console.WriteLine("\n第一种装扮:");            TShirts dtx = new TShirts();            BigTrouser kk = new BigTrouser();            dtx.Decorate(xc);            kk.Decorate(dtx);            kk.Show();            Console.Read();        }    }    class Person    {        public Person()        { }        private string name;        public Person(string name)        {            this.name = name;        }        public virtual void Show()        {            Console.WriteLine("装扮的{0}", name);        }    }    class Finery : Person    {        protected Person component();        public void Decorate(Person component)        {            this.component = component;        }        public override void Show()        {            if (component != null)            {                component.Show();            }        }    }    class TShirts : Finery    {        public override void Show()        {            Console.Write("大体恤");            base.Show();        }    }    class BigTrouser : Finery    {        public override void Show()        {            Console.Write("垮裤");            base.Show();        }    }

优点:

     把类中的装饰功能从类中 搬移去除了,这样可以简化原有的类,有效的把类的核心职责和装饰功能区分开了,去除了重复的装饰逻辑,让代码更具有拓展性。

  


           


              

0 0
原创粉丝点击