给 objects 一个 id 并通过所述 id 引用它的自动方法?
Automagic way of giving objects an id and referencing it by said id?
抱歉,垃圾标题,如果有这个问题的术语,请更改它!谢谢
如何清理代码中的以下 "pattern" 以更加自动化。我的意思是我可以创建一个新的 object 来扩展 Foo 而不必为所述 object 创建 Foo 的静态字段成员并将其添加到哈希映射中。
class Foo {
protected int id;
public Foo(int id) { this.id = id; }
public static final int BAR = 0;
public static final int QUX = 1;
public static HashMap<Integer, Foo> FOOS = new HashMap<>();
static {
FOOS.put(BAR, new Bar());
FOOS.put(QUX, new Qux());
}
}
class Bar extends Foo {
public Bar() { this(Foo.BAR); }
}
class Qux extends Foo {
public Qux() { this(Foo.QUX); }
}
我的主要要求是我可以通过它的 ID 轻松解决每个 object,即没有幻数:
someArray[randomIndex] = Foo.BAR;
但他们仍然需要一个整数,这样我就可以放入一个随机数,它可以查找它引用的 object:
for (int i : someArray) {
// for simplicity pretend that all the values
// in someArray are all valid keys for the FOOS hashmap
System.out.println(Foo.FOOS.get(i).id);
}
有点老套,但您可以使用 enum Foo
来处理对象和 ID:
enum Foo {
QUX;
private static int idIncrementor = 0;
private int id;
Foo() {
this.id = idIncrementor++;
}
public int getId() {
return id;
}
}
然后将其嵌入处理映射的 FooManager
class 中:
class FooManager {
private static HashMap<Integer, Foo> foos = new HashMap<>();
static {
for(Foo foo : Foo.values()) {
foos.put(foo.getId(), foo);
}
}
public static Foo getFoo(int id) {
return foos.get(id);
}
//enum Foo goes here
}
然后您可以添加新的枚举,而不必担心每次都映射它们。
要访问对象,只需执行 FooManager.getFoo(#)
。
要查找对象的 id
:FooManager.Foo.QUX.getId()
.
抱歉,垃圾标题,如果有这个问题的术语,请更改它!谢谢
如何清理代码中的以下 "pattern" 以更加自动化。我的意思是我可以创建一个新的 object 来扩展 Foo 而不必为所述 object 创建 Foo 的静态字段成员并将其添加到哈希映射中。
class Foo {
protected int id;
public Foo(int id) { this.id = id; }
public static final int BAR = 0;
public static final int QUX = 1;
public static HashMap<Integer, Foo> FOOS = new HashMap<>();
static {
FOOS.put(BAR, new Bar());
FOOS.put(QUX, new Qux());
}
}
class Bar extends Foo {
public Bar() { this(Foo.BAR); }
}
class Qux extends Foo {
public Qux() { this(Foo.QUX); }
}
我的主要要求是我可以通过它的 ID 轻松解决每个 object,即没有幻数:
someArray[randomIndex] = Foo.BAR;
但他们仍然需要一个整数,这样我就可以放入一个随机数,它可以查找它引用的 object:
for (int i : someArray) {
// for simplicity pretend that all the values
// in someArray are all valid keys for the FOOS hashmap
System.out.println(Foo.FOOS.get(i).id);
}
有点老套,但您可以使用 enum Foo
来处理对象和 ID:
enum Foo {
QUX;
private static int idIncrementor = 0;
private int id;
Foo() {
this.id = idIncrementor++;
}
public int getId() {
return id;
}
}
然后将其嵌入处理映射的 FooManager
class 中:
class FooManager {
private static HashMap<Integer, Foo> foos = new HashMap<>();
static {
for(Foo foo : Foo.values()) {
foos.put(foo.getId(), foo);
}
}
public static Foo getFoo(int id) {
return foos.get(id);
}
//enum Foo goes here
}
然后您可以添加新的枚举,而不必担心每次都映射它们。
要访问对象,只需执行 FooManager.getFoo(#)
。
要查找对象的 id
:FooManager.Foo.QUX.getId()
.