2017-01-23 48 views
2

道歉的垃圾标题,如果有这个问题的条款,请改变它!谢谢。Automagic给对象一个id并通过所述id引用它的方式?

如何清理我的代码中的以下“模式”以更加自动化。通过这个我的意思是我可以创建一个扩展Foo的新对象,而不必为该对象创建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,即没有神奇数字:

someArray[randomIndex] = Foo.BAR; 

但是他们仍然需要有一个整数,这样我就可以把在一个随机数,它可以做一个查找它所引用的对象:一个有点hackish

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); 
} 
+0

你能设计一个完美的'hashCode()'吗? –

回答

0

,但你可以使用一个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 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(#)。 查找对象的idFooManager.Foo.QUX.getId()

+0

太棒了,谢谢! – flooblebit