假设我有一个名为“animal”的包,其中包括 Animal 父类,Cat 扩展自 Animal,Dog 也扩展自 Animal。然而,Animal 是这样设计的:
class Animal {
int amount;
Animal next; // Then a constructor initializes these.
drinkWater(int n) { ... }
}
Cat & Dog 类遵循以下结构:
class Cat extends Animal {
Cat(int amount, Animal next) {
super(amount, next);
}
@Override
drinkWater(int n) { .. }
}
他们每个人都有这样的方法drinkWater():
public void drinkWwater(int n) {
amount -= n;
if (amount < 0) amount = 0;
if (next != null) next.drinkWater(n);
}
我现在要做的是创建一个动物的“链接列表”,每个动物都按顺序喝水。但是,假设一只猫喝了 n 量的水,它会将 n+1 量的水传递给它。next
我的目的是找到一个解决方案来克服“不接触原始动物包装,而是改变每个动物的饮水行为”的问题。我带着一个“著名的”天真的解决方案来了一个类:
class InvokeStaticTypeBDrink {
static void typeBdrink(Animal animal, int n) {
animal.amount -= n;
if (animal.amount < 0) animal.amount = 0;
if (animal.next != null) {
if (animal instanceof Cat)
InvokeStaticTypeDrink.drinkWater(animal.next, n+1);
else if (animal instanceof Dog)
InvokeStaticTypeDrink.drinkWater(animal.next, n-1);
else
InvokeStaticTypeDrink.drinkWater(animal.next, n);
}
}
}
然后,我开始研究。因为这看起来确实是快速而肮脏的解决方案。
所以,我发现了一种叫做“访客模式”的设计模式。好吧,很酷的模式解决了双重调度的问题,但我这边有一个问题:可访问接口(声明了 accept() 方法)应该由原始动物“实现”。但是,我的目标是“不要对原始动物包装进行任何修改,而是要改变饮水行为”。我很确定我错过了一些东西。
那么,您认为稍微修改一下,访客模式仍然可以工作还是其他模式/解决方案会更好?谢谢。