2016-04-07 29 views
1

我有很多擴展的子類:如何獲得每班延期的唯一ID?

class FirstImplementation extends Mother { [...] 
class SecondImplementation extends Mother { [...] 
class ThirdImplementation extends Mother { [...] 

我所試圖做的是一個簡單的輕辦法知道Mother類的兩個實例具有相同的實現:

Mother a = new FirstImplementation(); 
Mother b = new SecondImplementation(); 
Mother c = new FirstImplementation(); 

a.sameKindOf(b); // return false; 
a.sameKindOf(c); // return true; 

我的想法是建立在每個Mother例如整數ID字段,只是它在sameKindOf功能比較:

public class Mother { 
    private final int ID; 

    protected Mother(int ID) { 
     this.ID = ID; 
    } 

    public int getID() { 
     return this.ID; 
    } 

    public boolean sameKindOf(Mother other) { 
     return this.ID == other.getID(); 
    } 
} 

Mother的每個擴展都應該用一個精確的ID來調用Mother的構造函數。

我的問題是:有沒有一種方法可以在每次創建新擴展時自動提供不同的ID,還是我必須自己做,並在每個構造器類中給出不同的編號?

如果沒有,是否有更簡單的方法來完成我所要做的事情?

+1

在這種特定的情況下,你不能使用'instanceof'anyway。但是,您可以執行'a.getClass()== b.getClass()'。 –

+0

如果你不想使用instanceof運算符,爲什麼不使用類比較。 '返回this.getClass()== other.getClass();' –

+0

@TeemuIlmonen它會像整數比較一樣快嗎?如果是,請重新發布您的評論作爲答案,我會接受它。 – Aracthor

回答

0

難道不

public boolean sameKindOf(Mother other) { 
    return this.getClass().equals(other.getClass()); 
} 

做的工作?

0

看看java.util.UUID class及其靜態工廠方法public static UUID nameUUIDFromBytes(byte[] name)。那是你在找什麼?

1

如果你有興趣只在ID式解決方案...嘗試使用以下機制:

在你Mother類中聲明protected static int childClassesNumber;。它將存儲所有唯一的孩子的數量被裝:

class Mother { 
    protected static int childClassesNumber = 0; 
    private final int ID; 

    protected Mother(int ID) { 
    this.ID = ID; 
    } 

    public int getID() { 
    return this.ID; 
    } 

    public boolean sameKindOf(Mother other) { 
    return this.ID == other.getID(); 
    } 
} 

然後,以確保每個孩子得到唯一的ID,你應該使用這樣的事情在每個孩子(這是不好):

class ChildOne extends Mother { 
    public static final int ID; 

    static { 
    ID = ++Mother.childClassesNumber; 
    } 

    public ChildOne() { 
    super(ID); 
    } 
} 

的ID將僅在類加載階段(僅一次)

方式進行,並(例如)ChildTwo

class ChildTwo extends Mother { 
    public static final int ID; 

    static { 
    ID = ++Mother.childClassesNumber; 
    } 

    public ChildTwo() { 
    super(ID); 
    } 
} 

之後,下面的代碼

System.out.println(new ChildOne().sameKindOf(new ChildOne())); 
System.out.println(new ChildOne().sameKindOf(new ChildTwo())); 

得到:

真正

這種機制有一個巨大的缺點 - 你應該把static初始化每個兒童。樣板代碼等等...所以我會建議你使用@Ash解決方案)