【Unity与23种设计模式】访问者模式(Visitor)
2017-09-01 16:08
627 查看
GoF中定义:
“定义一个能够在一个对象结构中对于所有元素执行的操作。访问者让你可以定义一个新的操作,而不必更改到被操作元素的类接口。”
暂时没有完全搞明白
直接上代码
文章整理自书籍《设计模式与游戏完美开发》 菜升达 著
“定义一个能够在一个对象结构中对于所有元素执行的操作。访问者让你可以定义一个新的操作,而不必更改到被操作元素的类接口。”
暂时没有完全搞明白
直接上代码
//访问者接口 public abstract class IShapeVisitor { public virtual void VisitSphere(Sphere theShpere) { } public virtual void VisitCube(Cube theCube) { } public virtual void VisitCylinder(Cylinder theCylinder) { } } //形状容器 public class ShapeContainer { List<IShape> m_Shapes = new List<IShape>(); public ShapeContainer() { } public void AddShape(IShape theShape) { m_Shapes.Add(theShape); } public void RunVisitor(IShapeVisitor theVisitor) { foreach (IShape theShape in m_Shapes) { theShape.RunVisitor(theVisitor); } } }
//形状的定义 public abstract class IShape { public abstract void RunVisitor(IShapeVisitor theVisitor); } //各形状的重新实现 public class Sphere : IShape { public override void RunVisitor(IShapeVisitor theVisitor) { theVisitor.VisitSphere(this); } } public class Cube : IShape { public override void RunVisitor(IShapeVisitor theVisitor) { theVisitor.VisitCube(this); } } public class Cylinder : IShape { public override void RunVisitor(IShapeVisitor theVisitor) { theVisitor.VisitCylinder(this); } }
//绘图功能的Visitor public class DrawVisitor : IShapeVisitor { public override void VisitSphere(Sphere theShpere) { base.VisitSphere(theShpere); Debug.Log("画Sphere"); } public override void VisitCube(Cube theCube) { base.VisitCube(theCube); Debug.Log("画Cube"); } public override void VisitCylinder(Cylinder theCylinder) { base.VisitCylinder(theCylinder); Debug.Log("画Cylinder"); } }
//测试类 public class TestVisitor { void UnitTest() { ShapeContainer theShapeContainer = new ShapeContainer(); theShapeContainer.AddShape(new Sphere()); theShapeContainer.AddShape(new Cube()); theShapeContainer.AddShape(new Cylinder()); theShapeContainer.RunVisitor(new DrawVisitor()); } }
文章整理自书籍《设计模式与游戏完美开发》 菜升达 著
相关文章推荐
- Java开发中的23种设计模式详解----访问者模式(Visitor)
- 23种设计模式之访问者模式(Visitor)
- 23种设计模式之访问者模式(Visitor)
- Java开发中的23种设计模式之二十一:访问者模式(Visitor)
- GoF23种设计模式之行为型模式之访问者模式
- 设计模式 ( 二十 ) 访问者模式Visitor(对象行为型)
- 23种设计模式(9):访问者模式
- 设计模式 ( 二十 ) 访问者模式Visitor(对象行为型)
- 【Unity与23种设计模式】解释器模式(Interpreter)
- 【设计模式】—— 访问者模式Visitor
- 【23种设计模式】之 访问者模式(Visitor Pattern )
- GoF23种设计模式之行为型模式之访问者模式
- C#设计模式之Visitor访问者模式解决长隆欢乐世界问题实例
- Java23种设计模式——访问者模式
- 设计模式学习笔记——访问者(Visitor)模式
- 步步为营 .NET 设计模式学习笔记 二十一、Visitor(访问者模式)
- 设计模式之二十四:访问者模式(Visitor)
- 23种设计模式之访问者模式
- 设计模式读书笔记:Visitor(访问者)
- 设计模式学习笔记--访问者(Visitor)模式