场景
场景:
(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.总结
- 组合模式是在对象内部本身做的逻辑迭代
- 访问者模式是把组合模式里面的逻辑迭代行为封装到Vistor中,对象的行为被抽离出去,便于行为修改扩展,我们操作对象时候,只需要传递这个行为,类似于发出指令。
- 访问者模式,一般就是跟组合模式结合起来使用的
- 组合模式代表了一种复杂的对象的类型,如果你后面要给树形的数据结构增加个什么功能,修改代码可能会比较麻烦
- 但是如果采用访问者模式来做,你可以在任何时候给树形的数据结构增加任何的功能(只需要访问者自己定义方法-行为,传递给对象即可)