【发布时间】:2016-11-25 15:30:40
【问题描述】:
考虑以下情况:
public abstract class AnimalFeed{
}
public class FishFeed extends AnimalFeed{
}
public class BirdFeed extends AnimalFeed{
}
public abstract class Animal{
public void eat(AnimalFeed somethingToEat)
}
现在我想定义一个扩展“动物”的“鸟”类,确保当鸟吃东西时,它只吃鸟食。
一种解决方案是指定一种合约,其中“吃”的调用者必须传递适当提要的实例
public class Bird extends Animal{
@Override
public void eat(AnimalFeed somethingToEat){
BirdFeed somethingGoodForABird
if(somethingToEat.instanceOf(BirdFeed)){
somethingGoodForABird = (BirdFeed) somethingGoodForABird
}else{
//throws error, complaining the caller didn't feed the bird properly
}
}
}
将参数的责任委托给调用者是否可以接受?如何强制调用者传递参数的特化?是否有替代设计解决方案?
【问题讨论】:
标签: java inheritance design-patterns polymorphism