设计模式之访问者模式:动态的给目标对象增加新功能

场景

场景:

(1)父部门->子部门->子部门

(2)我们要对部门树,删除一个父部门以及其下所有的子部门

内容

1.使用访问者模式

将组合模式下内部迭代逻辑抽象到外部visitor里面的某个发方法。

1.类图
2.代码
复制代码
public class VisitorPattern {
    public static void main(String[] args) {
        //1.根部门
        Department rootDept = new Department("父部门");

        //2.子部门
        Department subDept1 = new Department("子部门1");
        Department subDept2 = new Department("子部门2");

        //3.叶子部门
        Department leafDept1 = new Department("叶子部门1");
        Department leafDept2 = new Department("叶子部门2");
        Department leafDept3 = new Department("叶子部门3");

        //4.组装数据
        subDept1.getChildren().add(leafDept1);
        subDept1.getChildren().add(leafDept2);
        subDept2.getChildren().add(leafDept3);

        rootDept.getChildren().add(subDept1);
        rootDept.getChildren().add(subDept2);
        rootDept.accept(new RemoveVisitor());
    }

    //===============访问者================
    public interface Visitor{
        void visit(Department dept);
    }

    public static class RemoveVisitor implements Visitor{

        public void visit(Department dept) {
           if (dept.getChildren().size()>0){
               for (Department children:dept.getChildren()){
                   children.accept(this);
               }
           }
            System.out.println("删除部门【" + dept.getName() + "】");
        }
    }

    //===============定义实体===============
    public static class Department{
        private String name;
        private List<Department> children = new ArrayList<Department>();

        public void accept(Visitor visitor){
            visitor.visit(this);
        }

        public Department(String name){
            this.name=name;
        }


        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public List<Department> getChildren() {
            return children;
        }

        public void setChildren(List<Department> children) {
            this.children = children;
        }
    }
}

2.总结

  1. 组合模式是在对象内部本身做的逻辑迭代
  2. 访问者模式是把组合模式里面的逻辑迭代行为封装到Vistor中,对象的行为被抽离出去,便于行为修改扩展,我们操作对象时候,只需要传递这个行为,类似于发出指令。
  3. 访问者模式,一般就是跟组合模式结合起来使用的
  4. 组合模式代表了一种复杂的对象的类型,如果你后面要给树形的数据结构增加个什么功能,修改代码可能会比较麻烦
  5. 但是如果采用访问者模式来做,你可以在任何时候给树形的数据结构增加任何的功能(只需要访问者自己定义方法-行为,传递给对象即可)
相关推荐
蜜獾云3 小时前
设计模式之策略模式:替换掉糟糕的if else语句实现面向对象编程而非面向过程
设计模式·策略模式
蜜獾云3 小时前
设计模式之状态模式:封装数据的状态流转逻辑
设计模式·状态模式
Serene_Dream3 小时前
深度解析设计模式:单例模式(Singleton Pattern)
单例模式·设计模式
朱一头zcy4 小时前
设计模式入门:最简单的单例模式
笔记·单例模式·设计模式
kuntli4 小时前
23种设计模式全解析
设计模式
海特伟业19 小时前
隧道调频广播覆盖-隧道调频广播无线覆盖系统建设要点、难点分析与解决应对
运维·设计模式
sg_knight19 小时前
设计模式实战:享元模式(Flyweight)
python·设计模式·享元模式·flyweight
Swift社区1 天前
AI 时代,ArkUI 的设计模式会改变吗?
人工智能·设计模式