Unity设计模式之装饰模式的使用

来源:互联网 发布:会计怎么学 知乎 编辑:程序博客网 时间:2024/06/05 14:25

装饰模式(Decorator)又叫装饰者模式,在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。,就增加功能来说,装饰模式比生成子类更加灵活。
下面上代码让大家更好的了解:
首先是Component类,它定义了一个对象接口,可以给这些对象动态的添加职责

using System;namespace DecoratorPackage{     abstract  class Component    {        public abstract void Operation();    }}

然后是ConcreteComponent类,它定义了一个具体的对象,也可以给这个对象添加一些职责

using System;using UnityEngine;namespace DecoratorPackage{     class ConcreteComponent : Component    {        public override void Operation ()        {            Debug.Log ("具体对象操作");        }    }}

接下来是装饰抽象类,Decorator类也就是装饰模式的精髓所在

using System;namespace DecoratorPackage{     class Decorator :Component    {        protected  Component component;        public void SetComponent(Component component)        {            this.component = component;        }        public override void Operation ()        {            if (component != null) {                component.Operation();            }        }    }}

然后是具体细分的职责类A 和 类B

using System;using UnityEngine;namespace DecoratorPackage{     class ConcreteDecoratorA :Decorator    {        private string addedState;        public override void Operation ()        {            base.Operation ();            addedState = "A中特有的变量";            Debug.Log ("具体装饰对象对A的操作");        }    }}
using System;using UnityEngine;namespace DecoratorPackage{     class ConcreteDecoratorB :Decorator    {        public override void Operation ()        {            base.Operation ();            AddedBehavior ();            Debug.Log ("具体对象对B的操作");        }        private void AddedBehavior()        {            Debug.Log ("B中特有的方法");        }    }}

最后是客户端代码

using System;using UnityEngine;namespace DecoratorPackage{    public class Client:MonoBehaviour    {        void Start()        {            ConcreteComponent c = new ConcreteComponent ();            ConcreteDecoratorA d1 = new ConcreteDecoratorA ();            ConcreteDecoratorB d2 = new ConcreteDecoratorB ();            d1.SetComponent (c);            d2.SetComponent (d1);            d2.Operation ();        }    }}
0 0
原创粉丝点击