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

场景

场景:

(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. 但是如果采用访问者模式来做,你可以在任何时候给树形的数据结构增加任何的功能(只需要访问者自己定义方法-行为,传递给对象即可)
相关推荐
武藤一雄1 天前
C# 异步回调与等待机制
前端·microsoft·设计模式·微软·c#·.netcore
he___H1 天前
Spring中的设计模式
java·spring·设计模式
程序员小寒1 天前
JavaScript设计模式(八):命令模式实现与应用
前端·javascript·设计模式·ecmascript·命令模式
程序员榴莲2 天前
设计模式之GoF设计模式(单例模式
单例模式·设计模式
砍光二叉树2 天前
【设计模式】行为型-解释器模式
设计模式·解释器模式
砍光二叉树2 天前
【设计模式】行为型-备忘录模式
设计模式·备忘录模式
光影少年2 天前
实现发布订阅模式
前端·javascript·设计模式
无籽西瓜a2 天前
【西瓜带你学设计模式 | 第十一期 - 模板方法模式】模板方法模式 —— 流程骨架与钩子实现、优缺点与适用场景
java·后端·设计模式·软件工程·模板方法模式
砍光二叉树2 天前
【设计模式】行为型-中介者模式
设计模式·中介者模式
sanzk2 天前
工厂方法模式
设计模式