【Unity与23种设计模式】访问者模式(Visitor)

时间:2022-11-05 08:33:44

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());
}
}

文章整理自书籍《设计模式与游戏完美开发》 菜升达 著