Unity设计模式之装饰模式的使用
2015-05-24 12:58
417 查看
装饰模式(Decorator)又叫装饰者模式,在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。,就增加功能来说,装饰模式比生成子类更加灵活。
下面上代码让大家更好的了解:
首先是Component类,它定义了一个对象接口,可以给这些对象动态的添加职责
然后是ConcreteComponent类,它定义了一个具体的对象,也可以给这个对象添加一些职责。
接下来是装饰抽象类,Decorator类也就是装饰模式的精髓所在
然后是具体细分的职责类A 和 类B
最后是客户端代码
下面上代码让大家更好的了解:
首先是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 (); } } }
相关文章推荐
- java设计模式--装饰器设计模式(javaIO设计使用)
- Unity设计模式之策略模式的使用
- Ruby使用设计模式中的代理模式与装饰模式的代码实例
- 实例讲解Ruby使用设计模式中的装饰器模式的方法
- 27 API-反射(类的加载器,反射的使用,动态代理)&设计模式(装饰设计模式,模版设计模式)&JDK新特性(JDK5,JDK6,JDK7,DK8)
- 【Unity】使用C#中的委托类型实现代理设计模式
- 使用Object-C实现23种设计模式之装饰器模式
- 【Unity与23种设计模式】装饰模式(Decorator)
- 【Unity与23种设计模式】装饰模式(Decorator)
- 包装设计模式(装饰设计模式)的使用
- JavaWeb学习篇——使用过滤器及装饰器设计模式解决全站乱码问题
- 编程经常使用设计模式具体解释--(中篇)(适配器、装饰、代理、外观、桥接、组合、享元)
- [置顶] 【设计模式】使用unity实现观察者模式(delegate,event)
- Unity应用架构设计(2)——使用中介者模式解耦ViewModel之间通信
- 【设计模式】使用unity实现策略模式(strategy model)
- 【设计模式】使用unity实现代理模式(Proxy mode)
- 【设计模式】使用unity实现模板模式(Template mode)
- 【设计模式】使用unity实现外观模式(Facade mode)
- 【设计模式】使用unity实现建造者模式(Builder mode)
- 【设计模式】使用unity实现状态模式(State mode)