以穿衣为例:

Component类:可以通过ConcreteComponent类动态添加职责

namespace Dacoration_Pattern.Class
{
    abstract class Component
    {
        public abstract void Show();
    }
}
View Code

ConcreteComponent类:定义了具体的职责

namespace Dacoration_Pattern.Class
{
    class ConCreteComponent:Component
    {
        private string name;
        public ConCreteComponent(string name)
        {
            this.name = name;
        }
        public override void Show()
        {
            Console.WriteLine("装扮的{0}",name);
        }
    }
}
View Code

Decorator类:

namespace Dacoration_Pattern.Class
{
    class Decorator:Component
    {
        protected Component person;
        public void Decorate(Component person)
        {
            this.person = person;
        }
        public override void Show()
        {
            if (person != null)
            {
                person.Show();
            }
        }
    }
}
View Code

ConcreteDecoratorA类:

namespace Dacoration_Pattern.Class
{
    class ConCreteDecoratorA:Decorator
    {
        public override void Show()
        {
            Console.WriteLine("大T恤");
            base.Show();
        }
    }
}
View Code

ConcreteDecoratorB类:

namespace Dacoration_Pattern.Class
{
    class ConcretrDecoratorB:Decorator
    {
        public override void Show()
        {
            Console.WriteLine("跨裤");
            base.Show();
        }
    }
}
View Code

ConcreteDecoratorC类:

namespace Dacoration_Pattern.Class
{
    class ConcreteDecoratorC:Decorator
    {
        public override void Show()
        {
            Console.WriteLine("皮鞋");
            base.Show();
        }
    }
}
View Code

客户端代码(TestMain)类:

namespace Dacoration_Pattern
{
    class TestMain
    {
        static void Main(string[] args)
        {
            ConCreteComponent person = new ConCreteComponent("张三");
            Console.WriteLine("第一种装扮:");
            ConCreteDecoratorA ConA = new ConCreteDecoratorA();
            ConcretrDecoratorB ConB = new ConcretrDecoratorB();
            ConcreteDecoratorC ConC = new ConcreteDecoratorC();
            ConA.Decorate(person);
            ConB.Decorate(ConA);
            ConB.Show();

            ConCreteComponent person1 = new ConCreteComponent("李四");
            Console.WriteLine("第二种装扮:");
            ConB.Decorate(person1);
            ConC.Decorate(ConB);
            ConC.Show();
            Console.ReadLine();
        }
    }
}
View Code

装饰模式结束!

 

posted on 2013-08-06 19:49  zxd543  阅读(150)  评论(0编辑  收藏  举报