• Unity设计模式——装饰模式


             装饰模式(Decorator),动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。

    Component类:

    1. abstract class Component : MonoBehaviour
    2. {
    3. public abstract void Operation();
    4. }

     ConcreteComponent类:

    1. class ConcreteComponent : Component
    2. {
    3. public override void Operation()
    4. {
    5. Debug.Log("具体对象操作");
    6. }
    7. }

     Decorator类:

    1. abstract class Decorator : Component
    2. {
    3. protected Component component;
    4. public void SetComponent(Component component)
    5. {
    6. this.component = component;
    7. }
    8. public override void Operation()
    9. {
    10. if(component != null)
    11. {
    12. component.Operation();
    13. }
    14. }
    15. }

     ConcreteDecoratorA类:

    1. class ConcreteDecoratorA : Decorator
    2. {
    3. //此类特有的功能,区别于ConcreteDecoratorB
    4. private string addState;
    5. public override void Operation()
    6. {
    7. //首先运行元Component的Operation()
    8. //再执行本类功能,对原Component进行修饰
    9. base.Operation();
    10. addState = "new state";
    11. Debug.Log("具体装饰对象A的操作");
    12. }
    13. }

      ConcreteDecoratorB类:

    1. class ConcreteDecoratorB : Decorator
    2. {
    3. public override void Operation()
    4. {
    5. //首先运行元Component的Operation()
    6. //再执行本类功能,对原Component进行修饰
    7. base.Operation();
    8. AddBehavior();
    9. Debug.Log("具体装饰对象B的操作");
    10. }
    11. //本类特有的方法
    12. private void AddBehavior()
    13. {
    14. }
    15. }

    客户端

    1. class Main : MonoBehaviour
    2. {
    3. private void Start()
    4. {
    5. ConcreteComponent c = new ConcreteComponent();
    6. ConcreteDecoratorA a = new ConcreteDecoratorA();
    7. ConcreteDecoratorB b = new ConcreteDecoratorB();
    8. a.SetComponent(c);
    9. b.SetComponent(a);
    10. b.Operation();
    11. }
    12. }

    输出结果:

    具体装饰对象A的操作 具体装饰对象B的操作 具体对象操作

            装饰模式是利用SetComponent来对对象进行包装的。这样每个装饰对象的实现就和如何使用这个对象分离开了,每个装饰对象只关心自已的功能,不需要关心如何被添加到对象链当中。        

            如果只有一个Concrete Component类而没有抽象的Component类,那么Decorator类可以是Concrete Component的一个子类。同样道理,如果只有一个Concrete Decorator类,那么就没有必要建立一个单独的Decorator类,而可以把Decorator和Concrete Decorator的责任合并成一个类。

            起初的设计中,当系统需要新功能的时候,是向旧的类中添加新的代码。这些新加的代码通常装饰了原有类的核心职责或主要行为,但这种做法的问题在于,它们在主类中加入了新的字段,新的方法和新的逻辑,从而增加了主类的复杂度,而这些新加入的东西仅仅是为了满足一些只在某种特定情况下才会执行的特殊行为的需要。而装饰模式却提供了一个非常好的解决方案,它把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象,因此,当需要执行特殊行为时,客户代码就可以在运行时根据需要有选择地、按顺序地使用装饰功能包装对象了。

  • 相关阅读:
    JenkinsNote-服务迁移
    Flutter 没有完整的生命周期?
    云原生微服务架构及实现技术
    Java计算Date类相距天数、月数、年数、直接获取年月日
    kubesphere中间件部署
    kafka基本架构以及参数调优
    async与await
    四、考研C语言笔记——顺序结构
    java基础之浅聊阻塞队列BlockingQueue
    视效剧情口碑双爆棚!Netflix 现象级剧集《怪奇物语》第四季神级视效专访大揭秘!
  • 原文地址:https://blog.csdn.net/qq_29296473/article/details/133672069