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

场景

场景:

(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. 但是如果采用访问者模式来做,你可以在任何时候给树形的数据结构增加任何的功能(只需要访问者自己定义方法-行为,传递给对象即可)
相关推荐
饮水桶_T3 小时前
Java调用大语言模型 笔记
笔记·设计模式·电脑·ai编程
ssshooter1 天前
Replit 项目本地跑:一份实测过的改造清单
前端·后端·设计模式
饮水桶_T1 天前
Java调用大语言模型、多轮对话 笔记
笔记·算法·设计模式·电脑·ai编程
AI酒旅实战开发2 天前
旅行 AI Agent 的 7 种设计模式:从工具调用到交易闭环
人工智能·设计模式
geovindu4 天前
rust: Functional Options Pattern
开发语言·后端·设计模式·rust·函数式选项模式·惯用法型模式
geovindu5 天前
rust: Timing Functions Pattern
开发语言·后端·设计模式·rust·计时函数模式·性能分析型模式
Mh10 天前
我是如何设计品牌站组件库的?
前端·css·设计模式
是2的10次方啊11 天前
设计模式与生活·总论:AI 能替你砌墙,替不了你打地基
设计模式
dahaihua33311 天前
用 SysML 表达航电系统架构(附建模示例)
设计模式·重构·系统架构·集成测试·需求分析·学习方法
wy_hhxx12 天前
《Agent设计模式 图解可复用智能体架构》上篇内容整理
设计模式·架构·ai agent