对访客设计模式感到困惑周期示例动物
所以,我刚刚阅读了关于访客模式的信息,我发现访客和元素之间的来回非常奇怪!
基本上,我们调用元素,我们传递给访问者,然后元素将自己传递给访问者。然后访问者操作该元素。什么?为什么?这感觉太不必要了。我称之为“来回疯狂”。
因此,当需要在所有元素中实现相同的操作时,访问者的意图是将元素与其操作分离。这是为了万一我们需要使用新操作扩展我们的元素,我们不想进入所有这些类并修改已经稳定的代码。因此,我们在这里遵循开放/封闭原则。
为什么会有这么多来来回回,如果我们没有这个,我们会失去什么?
例如,我编写的代码牢记了该目的,但跳过了访问者模式的交互疯狂。基本上我有跳跃和进食的动物。我想将这些操作与对象分离,因此我将操作移动到“访客”。进食和跳跃会增加动物健康(我知道,这是一个非常愚蠢的例子......
public interface AnimalAction { // Abstract Visitor
public void visit(Dog dog);
public void visit(Cat cat);
}
public class EatVisitor implements AnimalAction { // ConcreteVisitor
@Override
public void visit(Dog dog) {
// Eating increases the dog health by 100
dog.increaseHealth(100);
}
@Override
public void visit(Cat cat) {
// Eating increases the cat health by 50
cat.increaseHealth(50);
}
}
public class JumpVisitor implements AnimalAction { // ConcreteVisitor
public void visit(Dog dog) {
// Jumping increases the dog health by 10
dog.increaseHealth(10);
}
public void visit(Cat cat) {
// Jumping increases the cat health by 20
cat.increaseHealth(20);
}
}
public class Cat { // ConcreteElement
private int health;
public Cat() {
this.health = 50;
}
public void increaseHealth(int healthIncrement) {
this.health += healthIncrement;
}
public int getHealth() {
return health;
}
}
public class Dog { // ConcreteElement
private int health;
public Dog() {
this.health = 10;
}
public void increaseHealth(int healthIncrement) {
this.health += healthIncrement;
}
public int getHealth() {
return health;
}
}
public class Main {
public static void main(String[] args) {
AnimalAction jumpAction = new JumpVisitor();
AnimalAction eatAction = new EatVisitor();
Dog dog = new Dog();
Cat cat = new Cat();
jumpAction.visit(dog); // NOTE HERE. NOT DOING THE BACK AND FORTH MADNESS.
eatAction.visit(dog);
System.out.println(dog.getHealth());
jumpAction.visit(cat);
eatAction.visit(cat);
System.out.println(cat.getHealth());
}
}