zoukankan      html  css  js  c++  java
  • 访问者模式

     不同的类,相同的方法名,我们都会想到抽象类,但是每个抽象方法里面又有很多if else 的各种条件 我们程序怎么应对呢。这时候我们的访问者模式就出来了。

    首先我们定义一个学生类,里面有个抽象方法,抽象方面有个接口 来转移我们方法的内容

       public abstract class Student
        {
            public int stId { get; set; }
            public string name { get; set; }
        
            public abstract void getvoid(Ivistorone vistorone);
        }
    }

    StudentForCommon  大学生类 基础这个抽象类,并调用接口的方法

        public class StudentForCommon : Student
        {
           public override void getvoid(Ivistorone vistorone)
            {
                vistorone.study(this);
            }
        }

    studentForboy 小学生类 同上处理

        public class studentForboy : Student
        {
           public override void getvoid(Ivistorone vistorone)
            {
                vistorone.study(this);
            }
    
        }

    Ivistorone 接口 实现 2个类的stude 方法

       public interface Ivistorone
        {
             void study(studentForboy sts);
             void study(StudentForCommon sts);
        }

    vistorone  继承接口  

      public   class vistorone: Ivistorone
        {
            public void study(studentForboy sts)
            {
                Console.WriteLine($"小学生上课时间9.00   学生姓名id:{sts.stId} 学生姓名{sts.name}");
            }
            public void study(StudentForCommon sts)
            {
                Console.WriteLine($"大学生上课时间10.00   学生姓名id:{sts.stId} 学生姓名{sts.name}");
            }
        }

    由于实现接口 我们可以产生多个访问者

      public   class vistorV2
        {
            public void study(studentForboy sts)
            {
                Console.WriteLine($"小学生上课时间19.00   学生姓名id:{sts.stId} 学生姓名{sts.name}");
            }
            public void study(StudentForCommon sts)
            {
                Console.WriteLine($"大学生上课时间20.00   学生姓名id:{sts.stId} 学生姓名{sts.name}");
            }
        }

    前端调用

             List<Vistoer.Student> lists = new List<Vistoer.Student>();
    
                        lists.Add(new studentForboy()
                        {
                            name = "陈晓勇",
                            stId = 1
                        });
                        lists.Add(new StudentForCommon() { 
                         name="jason",
                         stId=2
                        });
    
                        Ivistorone vistorone = new vistorone();
                        foreach (var item in lists)
                        {
                            //  item.study();
                            item.getvoid(vistorone);
    
                        }

    这样我们把逻辑指定到上端 ,有上端指定 具体实现那个接口 ,由抽象类 抽象方法掉哪个类的方法 做到 方法内的条件转移。。。

  • 相关阅读:
    谁把天才变成了魔兽
    NetBeans 时事通讯(刊号 # 35 Nov 20, 2008)
    Java Annotation 手册
    《程序设计实践》读书笔记一
    5分钟让你明白金融危机爆发原因
    NetBeans 6.5 正式版可以下载了!
    Java Annotation 入门
    有关睡觉的学问
    oracle sql日期比较:
    C++编写安全OCX,IE不弹出安全提示
  • 原文地址:https://www.cnblogs.com/jasontarry/p/15384532.html
Copyright © 2011-2022 走看看