【Unity与23种设计模式】装饰模式(Decorator)
GoF中定义:
“动态地附加额外的责任给一个对象。装饰模式提供了一个灵活的选择,让子类可以用来扩展功能。”
装饰模式一般用来增加新功能
它可以避免更改已经实现的程序代码
从而增加系统的稳定性,也变得更加灵活
装饰模式解决了C#不能多继承的问题
它通过从父类继承出一个不符合“类封装时的抽象定义”的子类
持有一个父类的对象
然后与要添加的功能组合
从而实现添加新功能的目标
//形状父类 public abstract class IShape { public abstract void Draw(); public abstract string GetPolygon(); } //形状子类 public class Sphere : IShape { public override void Draw() { Debug.Log("draw Sphere"); } public override string GetPolygon() { return "Sphere多边形"; } }
//“不符合类封装时的抽象定义”的子类 public abstract class IShapeDecorator : IShape { IShape m_Component; public IShapeDecorator(IShape theComponent) { m_Component = theComponent; } public override void Draw() { m_Component.Draw(); } public override string GetPolygon() { return m_Component.GetPolygon(); } }
//能附加额外功能的类 public abstract class IAdditional { public abstract void DrawOnShape(IShape theShape); } public class Border : IAdditional { public override void DrawOnShape(IShape theShape) { Debug.Log("draw Border"); } }
//Border装饰者 public class BorderDecorator : IShapeDecorator { Border m_Border = new Border(); public BorderDecorator(IShape theComponent) : base(theComponent) {} public override void Draw() { base.Draw(); m_Border.DrawOnShape(this); } public override string GetPolygon() { return base.GetPolygon(); } }
//测试类 public class TestDecorator { void UnitTest() { Sphere theSphere = new Sphere(); BorderDecorator theSphereWithBorder = new BorderDecorator(theSphere); theSphereWithBorder.Draw(); } }
文章整理自书籍《设计模式与游戏完美开发》 菜升达 著