背景
示例
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();
}
}
}
网友评论