C# 设计模式(10)装饰器模式
装饰器模式
1.继承+组合
2. AOP编程思想的一种实现
代码实现:
员工:
namespace DecoratorPattern { public abstract class AbstractEmployee { public int Id { get; set; } public string Name { get; set; } public abstract void Work(); } public class Employee : AbstractEmployee { public override void Work() { Console.WriteLine($"{this.GetType().Name} 上班八小时."); } } }
装饰器:
namespace DecoratorPattern.Decorator { public class BaseEmployeeDecorator:AbstractEmployee { private readonly AbstractEmployee _employee; public BaseEmployeeDecorator(AbstractEmployee employee) { _employee = employee; } public override void Work() { _employee.Work(); } } public class EmployeeSoftwareDecorator:BaseEmployeeDecorator { private readonly AbstractEmployee _employee; public EmployeeSoftwareDecorator(AbstractEmployee employee) : base(employee) { _employee = employee; } public override void Work() { _employee.Work(); Console.WriteLine($"{this.GetType().Name} 留下来加个班."); } } }
代码调用:
class Program { static void Main(string[] args) { AbstractEmployee employee = new Employee() { Id = 101, Name = "Alex" }; employee = new EmployeeSoftwareDecorator(employee); employee.Work(); } }
结果: