Unity 装饰器模式
初学者,自用笔记
在不修改原类、不通过大量继承的前提下,给对象动态叠加功能
- Component:抽象组件,定义统一操作(被装饰对象对外的共同接口)。
- ConcreteComponent:具体组件,原始实现(不带额外功能的“裸对象”)。
- Decorator:抽象装饰器,实现/继承 Component,并持有一个 Component 引用,用于包裹与转发调用。
- ConcreteDecorator:具体装饰器,在转发调用前/后附加额外行为(可叠加多个)。
常用于buff系统等......
简单例子
Component
// Component:抽象组件,定义统一操作(计算最终伤害)
public interface IDamage
{
int GetDamage();
}
ConcreteComponent
// ConcreteComponent:具体组件,原始实现(基础伤害)
public sealed class BaseDamage : IDamage
{
private readonly int _base;
public BaseDamage(int baseDamage)
{
_base = baseDamage;
}
public int GetDamage() => _base;
}
Decorator
// Decorator:抽象装饰器,持有一个 Component,并默认把调用转发给它
public abstract class DamageDecorator : IDamage
{
protected readonly IDamage Inner;
protected DamageDecorator(IDamage inner)
{
Inner = inner;
}
public virtual int GetDamage() => Inner.GetDamage();
}
ConcreteDecorator
// ConcreteDecorator:具体装饰器A(加固定值,比如“附加火焰伤害 +10”)
public sealed class AddDamage : DamageDecorator
{
private readonly int _add;
public AddDamage(IDamage inner, int add) : base(inner)
{
_add = add;
}
public override int GetDamage() => base.GetDamage() + _add;
}
查看23道真题和解析
