加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-13 20:15:31 所属栏目:百科 来源:网络整理
导读:分析详见: 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[]

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读