美文网首页
{C#}设计模式辨析.装饰器

{C#}设计模式辨析.装饰器

作者: 码农猫爸 | 来源:发表于2021-08-08 06:17 被阅读0次

    背景

    • 不修改旧类的前提下,通过嵌套类增加功能

    示例

    using static System.Console;
    
    namespace DesignPattern_Decorator
    {
        // 抽象类:保证子类互换性+共用方法
        public abstract class Character
        {
            public abstract void Show();
        }
    
        // 实体类,被装饰对象
        public class Hero : Character
        {
            public override void Show()
                => WriteLine("I am Mario.");
        }
    
        // 装饰处理类,可在实体类上增加功能
        // 抽象类,保证装饰后结果的互换性+禁止新建实例
        public abstract class Decorator : Character
        {
            private readonly Character hero;
    
            public Decorator(Character hero)
            {
                this.hero = hero;
            }
    
            public override void Show() => hero.Show();
        }
    
        // 装饰结果类
        public class Driver : Decorator
        {
            public Driver(Character hero) : base(hero) { }
    
            public override void Show()
            {
                base.Show();
                WriteLine("I am also a driver.");
            }
        }
    
        // 装饰结果类
        public class Teacher : Decorator
        {
            public Teacher(Character hero) : base(hero) { }
    
            public override void Show()
            {
                base.Show();
                WriteLine("I am also a teacher.");
            }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                var hero = new Hero();
                var driver = new Driver(hero);
                var teacher = new Teacher(driver);
                teacher.Show();
                ReadKey();
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:{C#}设计模式辨析.装饰器

          本文链接:https://www.haomeiwen.com/subject/flwbvltx.html