内嵌式访问者模式
就是一棵树上的所有节点都有一个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!
这种内嵌式访问者模式业务逻辑和控制逻辑耦合在一起,在节点很多的时候修改维护都很困难,下面将介绍另外一种访问者模式