2013-10-06 33 views
1

提供我的程序可以作为默认值访问的静态(最终)值的最佳方式是什么?什么是最有效的或最佳实践? 我使用普通的Java与AWT/Swing。提供静态(默认)值的最佳方法

我可以想象,例如编写一个类Default只包含可以被访问的公共常量。你会称之为“硬编码”吗?

另一个想法是在Android中提供资源文件中的值。但是接下来我需要一个在编译时解析文件并为其生成类的机制。如果没有Android SDK的Java存在这样的东西吗?

我对最佳实践和设计模式感兴趣。对我的问题的任何建议是受欢迎的。

+1

枚举是维护常量的一个不错的选择 –

+1

@JunedAhsan ...除了在与这个类似的情况下,当常量彼此很不相关时。 – dasblinkenlight

+0

@dasblinkenlight我不认为常量是不相关的。但用户知道最好的:-) –

回答

1

我可以想象,例如编写一个类Default只包含公共常量,然后可以访问。你会称之为“硬编码”吗?

当然,这将是硬编码。另一方面,所有最后的机会默认都是硬编码的,所以这根本不是问题。

您也可以为您可能使用的各种变量创建映射硬编码默认值,并在需要默认值时从该映射中读取。然而,这不会让编译器确保所引用的所有常量都存在,我认为这是首先为默认值创建类的要点。

我会去你的Default类的建议,并使用静态导入它的好和可读的解决方案。

1

通常常数属于它们所属的类。例如:

public class Service { 
    public static final int PORT = 8080; 

    public static final int TIMEOUT = 10_000; 

    public Service() { 
     // ... 
    } 
} 

public class AppWindow { 
    public static final boolean CENTER_WINDOW = false; 

    public static final int VISIBLE_LINES = 12; 

    public AppWindow() { 
     // ... 
    } 
} 

如果你想在常量是可配置的,最简单的办法就是让他们定义为系统属性:如果您想给用户配置的能力

public class Service { 
    public static final int PORT = Math.max(1, 
     Integer.getInteger("Service.port", 8080)); 

    public static final int TIMEOUT = Math.max(1, 
     Integer.getInteger("Service.timeout", 10_000)); 
} 

public class AppWindow { 
    public static final boolean CENTER_WINDOW = 
     Boolean.getBoolean("AppWindow.centerWindow"); 

    public static final int VISIBLE_LINES = Math.max(1, 
     Integer.getInteger("AppWindow.visibleLines", 12)); 
} 

在文件的默认设置,您可以从属性文件读取它们,只要任何含常量的类加载之前,它的完成:

Path userConfigFile = 
    Paths.get(System.getProperty("user.home"), "MyApp.properties"); 

if (Files.isReadable(userConfigFile)) { 
    Properties userConfig = new Properties(); 
    try (InputStream stream = 
      new BufferedInputStream(Files.newInputStream(userConfigFile))) { 
     userConfig.load(stream); 
    } 

    Properties systemProperties = System.getProperties(); 
    systemProperties.putAll(userConfig); 
    System.setProperties(systemProperties); 
} 

(我有刻意对过分简化属性文件的位置;每个操作系统都有关于这些文件位置的不同政策。)