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

分析详见: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();
    }
}


 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值