美文网首页
设计模式之访问者模式

设计模式之访问者模式

作者: smallstrong | 来源:发表于2017-05-16 15:58 被阅读20次

    访问者模式

    访问者模式UML.png

    例子以公司招聘查看简历为背景

    interface Visitor{
        void visitClerical(Clerical clerical);//查看文员简历
        void visitCoder(Coder coder);//查看程序员简历
    }    
    

    访问者接口,分别对ElementA与ElementB进行访问

    class HRVisitor{
        public void visitClerical(Clerical clerical){
            //HR关注文员简历XXXXX
        }
        
        public void visitCoder(Coder coder){
            //HR看码农简历,看经验看学校
        }
    }
    

    HR访问者

    class CTOVisitor{
        public void visitClerical(Clerical clerical){
            //CTO不关心文员简历,可是是空实现
        }
        
        public void visitCoder(Coder coder){
            //CTO看码农简历,看项目 看技能
        }
    }
    

    CTO访问者

    abstract class JobSeeker{
        public String name;
        public String school;
        public String skill;
        
        public JobSeeker(String name ,String school ,String skill){
            this.name = name;
            this.school = school;
            this.skill = skill;
        }
        
        public abstract void accept(Visitor visitor);
    }
    

    抽象求职者类

    class Clerical extends JobSeeker{
        public Clerical(String name ,String school ,String skill){
            super(name , school , skill);
        }
        public void accept(Visitor visitor){
            visitor.visitClerical(this);
        }
    }
    

    文员求职者

    class Coder extends JobSeeker{
        public Coder(String name ,String school ,String skill){
            super(name , school , skill);
        }
        public void accept(Visitor visitor){
            visitor.visitCoder(this);
        }
    }
    

    码农求职者

    public class JobStructure{
        List<JobSeeker> list = new ArrayList<>();
        
        public void seeResume(Visitor visitor){
            for(JobSeeker jobSeeker : list){
                jobSeeker.accept(visitor);
            }
        }
        
        public void addJobSeeker(JobSeeker jobSeeker){
            list.add(jobSeeker);
        }
    }   
    

    查阅简历类

    class CLient{
        public static void main(String[] args){
            JobStructure jobStructure = new JobStructure();
            jobStructure.addJobSeeker(new Coder("小强","清华","Android"));
            jobStructure.addJobSeeker(new Coder("小民","北大","Word"));
            jobStructure.seeResume(new CTOVisitor());
            jobStructure.seeResume(new HRVisitor());
        }
    }   
    

    客户端类,收集简历,CTO查看简历,HR查看简历

    相关文章

      网友评论

          本文标题:设计模式之访问者模式

          本文链接:https://www.haomeiwen.com/subject/tkmlxxtx.html