[英]How can i instantiate a different subclass based on common identifier (java)
I have a class for a tile.我有一个用于瓷砖的 class。
public abstract class Tile {
public Position pos;
public char chr;
}
And many different classes that extend tile.以及许多扩展 tile 的不同类。 Each subclass has its own identifier char.
每个子类都有自己的标识符 char。 Now I have a function that receives a char and a position and needs to create and return a new instance of a tile subclass fitting the char in given position.
现在我有一个 function 接收一个字符和一个 position 并且需要创建并返回一个瓷砖子类的新实例,该实例适合给定 position 中的字符。 Is there an elegant OOP way to do this other than run through all of the options?
除了运行所有选项之外,是否有一种优雅的 OOP 方法可以做到这一点?
So for me use of an identifier like this is a bit of a design flaw.所以对我来说,使用这样的标识符有点设计缺陷。
You could add something like the following to the abstract class:您可以在抽象 class 中添加类似以下内容:
public static Tile factory(char identifier, Position p) {
Tile value = null;
switch (identifier) {
case `x`: {
value = new XTile(p);
break;
}
default {
// throw an exception or provide a default
}
}
return value
}
Effective Java (third edition) Item 21 "Prefer Class hierarchies to tagged classes" might provide an alternative to your design.有效的 Java(第三版)第 21 项“首选 Class 层次结构而不是标记类”可能会为您的设计提供替代方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.