• java设计模式之访问者(二)内嵌式访问者


    内嵌式访问者模式

    就是一棵树上的所有节点都有一个visit方法,每个父节点定义子节点的访问顺序。

    因为访问逻辑都在节点内部,得名内嵌式访问者

    下面展示一个demo,家谱是典型的树状结构,爷爷下面又爸爸和叔叔,爸爸下面又我和兄弟,依次访问。

    public abstract class Node {
       abstract void visit();
    }
    
    
    @Data
    @NoArgsConstructor
    public class GrandFather {
        
        private Father father;
        private Uncle uncle;
    
        public GrandFather(Father father, Uncle uncle) {
            this.father = father;
            this.uncle = uncle;
        }
        
        public void visit() {
            System.out.println("I am GrandFather!");
            father.visit();
            uncle.visit();
        }
    }
    
    @Data
    @NoArgsConstructor
    public class Father extends Node {
        private Me me;
        private Brother brother;
    
        public Father(Me me, Brother brother) {
            this.me = me;
            this.brother = brother;
        }
    
        @Override
        void visit() {
            System.out.println("I am Father!");
            me.visit();;
            brother.visit();
        }
    }
    
    
    @AllArgsConstructor
    @Data
    public class Uncle extends Node {
        @Override
        void visit() {
            System.out.println("I am uncle!");
        }
    }
    
    @AllArgsConstructor
    @Data
    public class Me extends Node {
        @Override
        void visit() {
            System.out.println("I am me!");
    
        }
    }
    
    @Data
    public class Brother extends Node {
        @Override
        void visit() {
            System.out.println("I am brother!");
        }
    }

    执行访问

    public class App {
        public static void main(String[] args) {
            GrandFather grandFather = new GrandFather();
            Father father = new Father();
            Uncle uncle = new Uncle();
            Me me = new Me();
            Brother brother = new Brother();
            grandFather.setFather(father);
            grandFather.setUncle(uncle);
            father.setBrother(brother);
            father.setMe(me);
            grandFather.visit();
    
        }
    }

    展示结果

    I am GrandFather!
    I am Father!
    I am me!
    I am brother!
    I am uncle!

    这种内嵌式访问者模式业务逻辑和控制逻辑耦合在一起,在节点很多的时候修改维护都很困难,下面将介绍另外一种访问者模式

  • 相关阅读:
    SqlParameter构造函数让人大吃一斤
    ASP.NET的图片上传和显示
    不去琢磨什么CSS后代选择器之类的鸟玩意了
    datatable里添加一个标识列
    提高工作效率
    调试无法命中断点问题
    离DBA还有多远?
    开发守则
    方法或函数也可以用泛型
    母版页访问内容页
  • 原文地址:https://www.cnblogs.com/wangbin2188/p/16593972.html
Copyright © 2020-2023  润新知