我们在办公室进行了讨论,但双方都不相信。可以说我们有
enum Food {
CHICKEN, HAMBURGER, FISH;
}
我们需要 Dog 的多个实现,它们需要回答,他们是否快乐,这取决于他们是否喜欢给他们的食物,也许还有其他一些东西。它需要非常灵活。哪个更好: A:
abstract class Dog {
//not sure if this can be abstract in reality, but does it matter?
abstract Set<Food> getFavoriteFoods();
boolean isFoodOk(){
return getFavoriteFoods().contains(Food.CHICKEN);
}
//in reality sometimes more conditions are needed here...
boolean isHappy(){
return isFoodOk();
}
}
public class BullDog extends Dog {
static final Set<Food> FAVORITE_FOODS = new HashSet<Food>();
static {
FAVORITE_FOODS.add(Food.CHICKEN);
FAVORITE_FOODS.add(Food.FISH);
}
Set<Food> getFavoriteFoods(){
return FAVORITE_FOODS;
}
}
或乙:
abstract class Dog {
abstract boolean isHappy();
boolean isFoodOk(Set<Food> f){
return f.contains(Food.CHICKEN);
}
}
public class BullDog extends Dog {
static final Set<Food> FAVORITE_FOODS = new HashSet<Food>();
static {
FAVORITE_FOODS.add(Food.CHICKEN);
FAVORITE_FOODS.add(Food.FISH);
}
@Override
boolean isHappy() {
return isFoodOk(FAVORITE_FOODS);
}
}
如果答案将是人工智能将有另一个问题。
注意:我编辑了代码,因为那里有一个愚蠢的错误——当然 FAVORITE_FOODS 应该在 BullDog 中声明,而不是 Dog。但这并不能回答问题。