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

 

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

 

 

 

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

转载于:https://www.cnblogs.com/fws94/p/7463710.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值