我有一个下面的抽象类 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{ }
我的问题是:
如果有机会在基于 future 海洋生物子类的 Critter 类中添加新的行为(方法),您是否认为上述设计是一个缺陷?
如果是,您建议我如何继续?
附加信息: 此应用程序的其余类(与当前查询无关)是 Ocean 类、Point 类、SimText 类、Utility 类。
可以在 link 的查询部分看到完整的代码(如果需要)
最佳答案
接口(interface)定义通用的行为,抽象类提供通用的实现。因此,只需创建一个您的小动物实现的 Locatable 接口(interface):
public interface Locatable {
Point getLocation();
}
当你有新的行为时,只需创建新的接口(interface)来表示你的小动物实现的它们:
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);
}
关于java - 查询行为改变对设计的影响——OOP范式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22828547/