2012-04-13 2 views
5

난 작은 자바 게임을 쓰고 있어요에 저장 게임 설정 변수와 아래와 같은 클래스 구조에서 글로벌 게임 설정을 저장하고있다 :최선의 방법 자바

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 
} 

이 작업이 매우 편리하지만 이것이 받아 들여지는 패턴인지 알고 싶습니다.

답변

10

.properties 파일에 저장하십시오.

config.properties 그것을

// 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(...) 

읽기

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

것은 그것을

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

s로 사용 사물을 암시하고 변경 사항을 최소화하기 위해 다음과 같이 할 수 있습니다.

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 
} 
+1

Personality, 나는 차라리 그들을 POJO에 저장하고 (일부) XML 파일을 일부 XStream 라이브러리와 직렬화한다. 속성을 읽는 것보다 훨씬 편리합니다. 너무 게으른 별도의 대답을 쓸 수 있습니다. – bezmax

+0

+1 속성 : 그들은 죽었어, 모두 이해하고 최종 사용자가 편집 할 수있어. –

+0

유령 인자에서 속성을 숨기려면 정적 vars가있는 클래스를 사용하는 것이 보안면에서 .properties 파일보다 더 좋습니다. 클래스는 여전히 디 컴파일 될 수 있지만, 그것은 더 복잡한 작업입니다. –

1

실제로 작은 응용 프로그램 인 경우 수행 할 수 있습니다. 이상적은 아니지만 소규모로 너무 정교하게 이끌어 낼 필요가 없습니다.

그러나 속성 파일에서 해당 값을 읽으십시오.

관련 문제