装饰模式中的里氏代换——子类可以代替父类

分析详见:http://lvxingzhelimin.blog.163.com/blog/static/1707165502011101035413741/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Person xc = new Person("小菜");
            Console.WriteLine("\n第一种装扮:");

            TShirts dtx = new TShirts();
            BigTrouser kk = new BigTrouser();
            Sneaker pqx = new Sneaker();

            //具体装饰类继承了服饰类,服饰类继承了人类,所以具体装饰类也就继承了人类,
            //因此,具体装饰类就可以替换人类,这样装饰顺序就产生了不同的装饰风格。
            //里氏代换原则/依赖倒转原则
            pqx.Decorate(xc);
            kk.Decorate(pqx);
            dtx.Decorate(kk );
            dtx.Show();

            Console.Read();
        }
    }
}
//Person类(ConcreteComponent)
class Person
{
    public Person()
    { }

    //人的姓名
    private string name;
    public Person(string name)
    {
        this.name = name;
    }
    //装扮的对象描述
    public virtual void Show()
    {
        Console.WriteLine("装饰的{0}",name );

    }
}


//服饰类(Decorator):Person这个类没有必要知道Finery类的存在,Finery类的作用是对Person的功能的扩展
class Finery : Person
{
    protected Person component;

    //定义打扮的对象
    public void Decorate(Person component)
    {
        this.component = component;
    }

    //显示打扮的对象,重写父类(Person)方法
    public override void Show()
    {
        if (component != null)
        {
            component.Show();
        }
    }

}

//具体服饰类(ConcreteDecorator)
class TShirts : Finery
{
    public override void Show()
    {
        Console.WriteLine("大T恤");
        base.Show();
    }
}
class BigTrouser : Finery
{
    public override void Show()
    {
        Console.WriteLine("垮裤");        
        base.Show();
    }
}

class Sneaker : Finery
{
    public override void Show()
    {
        Console.WriteLine("破球鞋");
        base.Show();
    }
}
class LeatherShoes : Finery
{
    public override void Show()
    {
        Console.WriteLine("皮鞋");        
        base.Show();
    }
}

相关文章

迭代器模式(Iterator)迭代器模式(Iterator)[Cursor]意图...
高性能IO模型浅析服务器端编程经常需要构造高性能的IO模型,...
策略模式(Strategy)策略模式(Strategy)[Policy]意图:定...
访问者模式(Visitor)访问者模式(Visitor)意图:表示一个...
命令模式(Command)命令模式(Command)[Action/Transactio...
生成器模式(Builder)生成器模式(Builder)意图:将一个对...