访问者模式

设计模式/行为型设计模式

简述

封装一些施加于某种数据结构元素之上的操作。一旦这些操作需要修改的话,
接受这个操作的数据结构则可以保持不变

UML图

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public interface Food {
void eat(Animal animal);
}

@Slf4j
public class CatFood implements Food {
@Override
public void eat(Animal animal) {
animal.run();
log.debug(“猫粮 — “);
}
}

// 结构对象 环境
public class Context {
private List<Food> foods = new ArrayList<>();

public void add(Food food) {
foods.add(food);
}

public void visit(Animal animal) {
foods.forEach(food -> food.eat(animal));
}
}

// 客户端
public class Client {
public static void main(String[] args) {
Food catFood1 = new CatFood();
Food catFood2 = new CatFood();
Context context = new Context();
context.add(catFood1);
context.add(catFood2);
Animal cat = new Cat();
Animal dog = new Dog();
context.visit(cat);
context.visit(dog);
}
}