装饰模式

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

下面是书中,以小菜穿衣服为例子:


public class Test
{
    void Main()
    {
        Person xc = new Person("小菜");
        Debug.Log("第一种装扮:");

        TShirts t = new TShirts();
        Shooes s = new Shooes();
        BigTrouser b = new BigTrouser();

        t.Decorate(xc);
        s.Decorate(t);
        b.Decorate(s);

        b.Show();
    }

   
}

class Person
{
    public Person() { }

    private string name;
    public Person(string name)
    {
        this.name = name;
    }

    public virtual void Show()
    {
        Debug.Log(string.Format("装扮的{0}", name));
    }
}

//服饰类
class Finery : Person
{
    Person component;

    public void Decorate(Person com)
    {
        this.component = com;
    }

    public override void Show()
    {
        if (component != null)
            component.Show();
    }
}

//具体服饰类

class TShirts : Finery
{
    public override void Show()
    {
        Debug.Log("大TShirt");
        base.Show();
    }
}

class BigTrouser : Finery
{
    public override void Show()
    {
        Debug.Log("跨裤");
        base.Show();
    }
}

class Shooes : Finery
{
    public override void Show()
    {
        Debug.Log("拖鞋");
        base.Show();
    }
}

你可能感兴趣的:(装饰模式)