吉吉于

设计模式(4):装饰模式

特点:  

(1) 装饰对象和真实对象有相同的接口。这样客户端对象就可以以和真实对象相同的方式和装饰对象交互。

(2) 装饰对象包含一个真实对象的索引(reference)

(3) 装饰对象接受所有的来自客户端的请求。它把这些请求转发给真实的对象。

(4) 装饰对象可以在转发这些请求以前或以后增加一些附加功能。这样就确保了在运行时,不用修改给定对象的结构就可以在外部增加附加的功能。在面向对象的设计中,通常是通过继承来实现对给定类的功能扩展。

![Decorate.gif][1]

Person:

 

[代码如下]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;</p>

namespace Decorate
{
    class Person
    {
        private string _name;
        public Person() { }
        public Person(string name)
        {
            _name = name;
        }
        public virtual void Show()
        {
            Console.WriteLine("装扮的{0}",_name);
        }
    }
}</div> </div>

Decorator:

 

[代码如下]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;</p>

namespace Decorate
{
    abstract class Finery:Person
    {
        protected Person component;
        public void Decorate(Person component)
        {
            this.component = component;
        }
        public override void Show()
        {
            if (component != null)
            {
                component.Show();
            }
        }
    }
}</div> </div>

ConcreteDecorator:

 

[代码如下]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;</p>

namespace Decorate
{
    class TShirts:Finery
    {
        public override void Show()
        {
            Console.WriteLine("T恤");
            base.Show();
        }
    }
    class BigTrouser : Finery
    {
        public override void Show()
        {
            Console.WriteLine("垮裤");
            base.Show();
        }
    }
    class Sneakers : Finery
    {
        public override void Show()
        {
            Console.WriteLine("球鞋");
            base.Show();
        }
    }
  
}</div> </div>

Program:

 

[代码如下]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;</p>

namespace Decorate
{
    class Program
    {
        static void Main(string[] args)
        {
            Person person1 = new Person("Flowerowl");
            Console.WriteLine("装扮如下:");
            TShirts tshirt = new TShirts();
            BigTrouser bigtrouser = new BigTrouser();
            Sneakers sneaker = new Sneakers();

            tshirt.Decorate(person1);
            bigtrouser.Decorate(tshirt);
            sneaker.Decorate(bigtrouser);
            sneaker.Show();
            
        }
    }
}

 

 

 

 

  

转载请注明:于哲的博客 » 设计模式(4):装饰模式

[1]: http://lazynight.me/wp-content/uploads/2012/05/3246321439.gif