学习笔录——大话设计模式——装饰模式 装饰模式

学习笔录——设计模式

简介

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

代码示例

要求:在不影响一个Person类的情况下给它添加额外的功能


// 人
public class Person
{
    private string Name;
    public Person(string name)
    {
        this.Name = name;   
    }
    public Person()
    { }

    public void DoOtherThings()
    {
        System.Console.WriteLine("DoOtherThings");
    }

    // 增加一个为Person添加服装秀装扮的功能
    public virtual void Show()
    {
        System.Console.WriteLine($"装扮的{this.Name}");
    }
}

// 核心装饰类
public class Decorator : Person
{
    protected Person component;
    public void Decorate(Person compon)
    {
        this.component = compon;
    }

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

// T恤类
public class TShirt : Decorator
{
    public override void Show()
    {
        System.Console.WriteLine("穿T恤");
        base.Show();
    }
}

// 西装类
public class Suit : Decorator
{
    public override void Show()
    {
        System.Console.WriteLine("穿西服");
        base.Show();
    }
}

Main方法


static void Main(string[] args)
{
    Person p = new Person("hmy");
    TShirt t = new TShirt();
    Suit suit = new Suit();

    // t 装饰的是p 
    t.Decorate(p);

    // suit装饰的是 => t
    suit.Decorate(t);

    // show()先输出suit base是t t的base是p
    suit.Show();

    Console.Read();
}

个人理解,不足之处还请指教。

Decorator 继承 Person 从外类来扩展Person类的功能,但对于Person 它是无感的,装饰模式利用Decorator的Decorate方法来对对象进行包装,比如 t.Decorate(p); 它通过父类的装饰来对Person进行包装,suit.Decorate(t); 通过父类的装饰来对已经装饰过T恤的人进行装饰,而Person只负责展示(show)。suit.Show();先输出自身 再调用base.show() 此时Person引用为TShirt 接着输出 TShirt.Show(),再调用base.show() 此时Person引用为p 就是调用Person.Show();