我有一个下面的抽象类Critter,
/* Critter.java */
/**
* The abstract class Critter defines a base class for anything(which can be empty)
* that can exist at a specific location in the ocean.
* @author mohet01
*
*/
public abstract class Critter {
/**
* Below data member defines a location of a Critter in an Ocean
*/
Point location;
public Critter(int x, int y){
location = new Point(x,y);
}
public Point getLocation(){
return location;
}
/**
* This method computes the new value of location(which can be EMPTY) property of Critter.
* No operation is performed as this is a base class.
*/
public abstract Critter update(Ocean currentTimeStepSea);
}
目前有3个子类继承,分别是Shark类,Fish类和Empty类
/* Empty.java */
/**
* The Empty class defines itself as an entity as it has some meaning/significance
* being empty in an Ocean. Check update() method for more meaning.
* @author mohet01
*
*/
public class Empty extends Critter{ ...}
/* Shark.java */
/**
* The Shark class defines behavior of a Shark in an Ocean.
* @author mohet01
*
*/
public class Shark extends Critter{ }
/* Fish.java */
/**
* The Fish class defines the behavior of a Fish in an Ocean
* @author mohet01
*
*/
public class Fish extends Critter{ }
我的问题是:
如果有可能根据将来的海洋生物子类在Critter类中添加新的行为(方法),您是否认为上述设计有缺陷?
如果是,您如何建议我继续?
附加信息:
属于该应用程序的其余类(与当前查询无关)是Ocean类,Point类,SimText类,Utility类。
完整的代码可以在link的查询部分中看到(如果需要)
最佳答案
接口定义了共同的行为,抽象类提供了共同的实现。因此,只需创建一个由生物实现的Locatable接口:
public interface Locatable {
Point getLocation();
}
当您有新行为时,只需创建新接口来表示您的生物所实现的接口:
public class Fish implements Locatable, Prey {}
public class Shark implements Locatable, Predator {}
public interface Predator {
void eat(Prey prey);
}
public interface Prey {
void hideFrom(Predator predator);
}