java - 查询行为改变对设计的影响——OOP范式

标签 java oop

我有一个下面的抽象类 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/

相关文章:

c# - 在该类的静态方法中创建该类的实例是否干净?

java - 未初始化的整数相当于null

java - 如何双击 Selenium webdriver 中的 webElements 列表

java - 怎么把单词最后一个字母变成大写

java - 使用对象实例化测试代码的良好实践

java - 在 Java 迭代器中强制执行顺序

java - 如何处理复合模式中的添加、删除功能?

java - 关闭和访客模式之间有显着差异吗?

java - 收到有关 Eclipse/Java 应用程序中捕获的异常的通知

java - 为什么 Mockito 对 InputStreams 的行为很奇怪?