gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:20:16 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com