gpt4 book ai didi

java - 创建对象时使用 "new"变量

转载 作者:搜寻专家 更新时间:2023-10-30 19:53:42 25 4
gpt4 key购买 nike

我正在设计一个虚拟水族馆。我有一个类:鱼,我继承它来创建不同物种的类。用户可以在组合框中选择物种,然后单击按钮将鱼放入鱼缸。我使用以下代码创建鱼:

    switch(s){
case "Keegan" :
stock.add(new Keegan(this, x,y));
break;
case "GoldenBarb" :
stock.add(new GoldenBarb(this, x,y));

“stock”是一个 LinkedList,“s”是在 Jcombobox 中选择的字符串。就目前而言,当我添加一堆不同的物种时,我将不得不创建一个长开关。我希望代码看起来像:

stock.add(new s(this,x,y));

并省去了开关,这样我所要做的就是创建类并将其名称添加到组合框中并让它工作。有办法吗?感谢您的帮助。

最佳答案

你想使用一堆工厂对象,存储在你在 switch 中使用的字符串键下的 Map 中。

这些是您应该已经拥有的各种鱼的类。

abstract class FishBase {}

class Keegan extends FishBase {
Keegan(Object _this, int x, int y) {
// ...
}
}
class GoldenBarb extends FishBase {
GoldenBarb(Object _this, int x, int y) {
// ...
}
}

所有鱼类工厂的接口(interface)。鱼类工厂代表一种创造某种鱼类的方法。您没有提到构造函数签名是什么,所以我只选择了一些类型。

interface IFishFactory {
FishBase newFish(Object _this, int x, int y);
}

为每种鱼类型设置一个工厂。这些显然不需要是匿名类,我使用它们来减少困惑。

Map<String, IFishFactory> fishFactories = new HashMap<>();

fishFactories.put("Keegan", new IFishFactory() {
public FishBase newFish(Object _this, int x, int y) {
return new Keegan(_this, x, y);
}
});

fishFactories.put("GoldenBarb", new IFishFactory() {
public FishBase newFish(Object _this, int x, int y) {
return new GoldenBarb(_this, x, y);
}
});

然后只需使用您已有的字符串从 Map 中选择工厂。您可能想检查给定名称的工厂是否存在。

stock.add(fishFactories.get(s).newFish(this, x, y));

现在,如果您所有的鱼类都具有完全相同的构造函数签名,您可以创建一个工厂类来使用反射处理所有这些类,并摆脱一些样板。

class ReflectionFishFactory implements IFishFactory {
Constructor<? extends FishBase> fishCtor;
public ReflectionFishFactory(Class<? extends FishBase> fishClass)
throws NoSuchMethodException {

// Find the constructor with the parameters (Object, int, int)
fishCtor = fishClass.getConstructor(Object.class,
Integer.TYPE,
Integer.TYPE);
}


@Override
public FishBase newFish(Object _this, int x, int y) {
try {
return fishCtor.newInstance(_this, x, y);
} catch (InstantiationException
| InvocationTargetException
| IllegalAccessException e) {
// this is terrible error handling
throw new RuntimeException(e);
}
}
}

然后为每个适用的子类注册它。

for (Class<? extends FishBase> fishClass : 
Arrays.asList(Keegan.class,GoldenBarb.class)) {
fishFactories.put(fishClass.getSimpleName(),
new ReflectionFishFactory(fishClass));
}

关于java - 创建对象时使用 "new"变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13907977/

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