zoukankan      html  css  js  c++  java
  • 【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());
        }
    }

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

  • 相关阅读:
    I-string_2019牛客暑期多校训练营(第四场)
    hackerrank Palindromic Border
    hackerrank Circular Palindromes
    uoj424
    bzoj5384
    uoj450
    QTP 表格的导入导出异常信息 笔记
    QTP基本循环异常遍历(代码方式实现)
    QTP基本循环正常遍历(代码方式实现)
    《大道至简》读后感
  • 原文地址:https://www.cnblogs.com/fws94/p/7463710.html
Copyright © 2011-2022 走看看