5

私は小さなJavaゲームを書いていて、グローバルゲーム設定を以下のようなクラス構造に保存しています:

public class Globals {
    public static int tileSize = 16;
    public static String screenshotDir = "..\\somepath\\..";
    public static String screenshotNameFormat = "gameNamexxx.png";
    public static int maxParticles = 300;
    public static float gravity = 980f;
    // etc
}

これは非常に便利ですが、これが受け入れられたパターンであるかどうかを知りたいです。

4

2 に答える 2

12

ファイルに保存し.propertiesます。

config.properties

tile.size=16
screenshot.dir=..\\somepath\\..

それを読む

// Make sure this happens only the first time you start your application
Properties properties = new Properties();
// You can use FileInputStream, ClassLoader.getResourceAsStream or a reader too
properties.load(...)

それを使用する

int tileSize = Integer.valueOf(properties.getProperty("tile.size"));
String screenshotDir = properties.getProperty("screenshot.dir");

物事を単純化し、変更を最小限に抑えるために、次のようなこともできます。

public class Globals {
    private static final Properties properties = new Properties();

    static {
        // do the loading here
    }

    public static final int TILE_SIZE = 
        Integer.valueOf(properties.getProperty("tile.size"));
    public static final String SCREENSHOT_DIR = 
        properties.getProperty("screenshot.dir");
    // etc
}
于 2012-04-13T12:17:22.000 に答える
1

それが本当に小さなアプリケーションであれば、それで十分です。理想的ではありませんが、小規模で洗練されすぎても意味がありません。

ただし、これらの値をプロパティファイルから読み取ります。

于 2012-04-13T12:18:18.103 に答える