2011-11-04 74 views
0

我有一個軟件設置2層,一個核心層和一個客戶特定層。核心層定義了客戶特定層應該能夠擴展的常量。更具體的:Java可擴展常量

public class CoreConstants 
{ 
    public static long CORE_CONSTANT_1 = 1; 
    public static long CORE_CONSTANT_2 = 2; 
} 

客戶特定圖層應該能夠添加僅用於客戶特定圖層的常量。點子:

public class CustomerConstants extends CoreConstants 
{ 
    public static long CUSTOMER_CONSTANT_1 = 1000; // starting range = 1000 
} 

有沒有更常見的方法來處理?

更多信息:繼承的原因是定義客戶特定常量的起始範圍。在CoreConstants類中,我可以設置客戶特定常量的初始值。客戶特定的常量可以定義爲:

public static long CUSTOMER_CONSTANT_1 = customStartValue + 1; 
public static long CUSTOMER_CONSTANT_2 = customStartValue + 2; 

回答

3

整型常量一般都帶有enum好多了更換,你可以實現你想要使用的枚舉的接口是什麼。

interface CoreConstant { 
    int intValue(); 
} 

enum CoreConstants implements CoreConstant { 
    CORE_CONSTANT_1(1), 
    CORE_CONSTANT_2(2); 
    private final int intValue; 
    public CoreConstants(int intValue) { this.intValue = intValue; } 
    public int intValue() { return intValue; } 
} 

interface CustomerConstant extends CoreConstant {} 

enum CustomerConstants implements CustomerConstant { 
    CUSTOMER_CONSTANT_1(1000); 
    private final int intValue; 
    public CustomerConstants(int intValue) { this.intValue = intValue; } 
    public int intValue() { return intValue; }  
} 

也許你可以改善使用枚舉內的代表團,使用IntConstant類的設計。不幸的是你的情況,你不能擴展枚舉。結果是在枚舉類中有一些代碼重複。否則,如果你想留在公共靜態詮釋模型,然後使用一個接口,而不是一個類,並最終確定常量。

interface CoreConstants { 
    public static final int CORE_CONSTANT_1 = 1; 
} 
+0

感謝關於枚舉,可能適用於我的情況。關於使用接口,爲什麼會比使用類更好? –

+0

如果「類型」僅僅是一個常量容器,那麼你永遠不應該能夠實例化它。你可以通過私有化構造函數來做到這一點,但是使用接口通常會更清晰。除非你確實需要一些功能,比如'valueOf(String)'方法。在這種情況下,您將返回一個類... – ptomli

+2

@ptomli:用於保存常量的接口通常被視爲反模式。請參閱http://en.wikipedia.org/wiki/Constant_interface。在這種情況下,不需要公共的靜態最終修飾符,因爲接口的所有字段都是隱式的public,static和final。 –

1

沒有理由在這兩個類之間有繼承機制。繼承用於多態,並且此處只有靜態成員。只有兩個不同的課程。我甚至可以讓他們最終與非可實例:

public final class CoreConstants { 
    /** 
    * Private constructor to prevent unnecessary instantiations 
    */ 
    private CoreConstants() { 
    } 
} 
+0

繼承的原因現在我已經定義了客戶特定常量的起始值。將此信息添加到原始問題。 –