提供静态(默认)值的最佳方式



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

例如,我可以想象编写一个类Default,该类仅包含随后可以访问的公共常量。你会称之为"硬编码"吗?

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

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

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

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

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

我会接受您对Default类的建议,并使用它的静态导入来获得漂亮且可读的解决方案。

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

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

(为了简洁起见,我故意过度简化了属性文件的位置;每个操作系统对此类文件的位置都有不同的策略。

最新更新