设计模式------装饰模式(二)

2014-11-23 21:51:04 · 作者: · 浏览: 65
D4KPHA+CjxpbWcgc3JjPQ=="https://www.cppentry.com/upload_files/article/76/1_r46kn__.jpg" alt="\">

(2)代码

person类:

 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();
    }
各种服饰子类:

 //大T恤
    class TShirts : Finery
    {
        public override void Show()
        {
            Console.Write("大T恤 ");
        }
    }
    //垮裤
     ...
    //皮鞋
    ...
客户端:
static void Main(string[] args)
        {
            Person xc = new Person("小菜");
            Console.WriteLine("\n第一种装扮:");
            Finery dtx = new TShirts();
            Finery kk = new BigTrouser();
            Finery pqx = new Sneakers();

            dtx.Show();
            kk.Show();
            pqx.Show();
            xc.Show();

            Console.WriteLine("\n第二种装扮:");
            ...
            Console.Read();
        }

(3)评价:“服饰类”与“人类”分离,但服饰类是装饰人类的,二者有关系,客户端的代码显得离散,低内聚,需要在内部进行组装,把所需的功能按正确的顺序串联起来进行控制。


2.使用装饰模式

(1)代码结构图:

\

(2)代码:

Person类

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("大T恤 ");
            base.Show();
        }
    }
//其余类类似
    class BigTrouser : Finery
    ...
    class Sneakers : Finery
    ...
    class Suit : Finery
    ...
客户端:

static void Main(string[] args)
        {
            Person xc = new Person("小菜");

            Console.WriteLine("\n第一种装扮:");

            Sneakers pqx = new Sneakers();
            BigTrouser kk = new BigTrouser();
            TShirts dtx = new TShirts();
       //装饰过程
            pqx.Decorate(xc);
            kk.Decorate(pqx);
            dtx.Decorate(kk);
            dtx.Show();

            Console.WriteLine("\n第二种装扮:");
            ...
            Console.Read();
        }
    }
效果图:



评价:使用装饰模式,将person类中的穿衣打扮功能从person中分离出来,遵守了开闭原则,简化了原有的类,有效地把类的核心职责和装饰功能区分开,去除相关类中重复的装饰逻辑。把每个要装饰的功能放在单独的类中,并让这个类包装它所要修饰的对象,这样客户代码就可以在运行时根据需要有选择地、按顺序地使用装饰功能包装对象。