2016-12-24 45 views
1

基本上,我的問題與this一樣,除了我必須在特定的時間點上對每個常量執行代碼。沒有巨大的「常量」類存儲遊戲對象常量

更具體地說,我試圖讓我的遊戲插件更堅持面向對象和良好的設計原則和標準。以前,我們有巨大的類包含遊戲對象常量,巨大的靜態register方法(例如registerFirearmsregisterArmor)將這些對象註冊到其適當的註冊表,然後將它們分配給它們的全局常量。

例如:

public class Items { 
    public static Item firearm; 

    public static void register() { 
     registerFirearms(); 
    } 

    public static void registerFirearms() { 
     firearm = new FirearmItem(); 
     Registry.register(firearm); 
    } 
} 

在遊戲加載過程中適當的時候,Items.register();會被調用,所有在類中的值將是準備在整個插件使用。

我只是不太確定我應該如何去存儲這些對象實例,而沒有一些可怕的不可維護的幾千行類。

+0

有很多這樣做的遊戲,比如'Minecraft'和'Terraria'。他們有每個〜1000行的「常量」文件。所以我認爲這是通常的做法(根本不是專家) – ItamarG3

+0

啊,有時間加入我的肥皂盒。將常量分組,而不是通過它們不變的事實,而是通過它們在邏輯上屬於您的設計的位置。就像對另一個問題的接受答案一樣。 –

+0

可能相關:http://softwareengineering.stackexchange.com/questions/338805/is-it-bad-design-to-leave-a-constants-class-when-refactoring –

回答

0

如何將所有項目存儲到配置文件(甚至更好的XML)然後讓您的Items.register();讀取文件並初始化所有項目?

我會做類似

public class Item { 
    public Item(String type /* any other thing about the item*/) { 
     // do your stuff... 
    } 
} 

public interface ItemCollection { 
    public void register() throws YourProjectException; 
} 

public interface ItemSet implements ItemCollection { 
    private final java.util.Set<Item> items; 

    public void register() throws YourProjectException { 
     try { 
      // open the file 
      // read each item and store it in "i" 
      items.add(i); // you must override the equals method if you want each item to be added just once... 
      // close the file 
     } catch(Exception ex) { // even better if you manage each exception separately 
      // manage the exception 
      throw new YourProjectException(); 
     } 
    } 
} 
1

看來,每一個項目最終需要與註冊處註冊。因此,一個長長的東西無論如何都是不可避免的。因此,我認爲你不一定要看代碼組織問題。在我看來,這是一個問題:沒有足夠的數據管理工具來處理數據。

如果可能的話,我會建議管理java代碼之外的數據,探索像SQLite這樣的選項。通過這種方式,您可以配置數據庫以使維護項目數據的過程更加高效。然後更改您的java代碼,以便通過將查詢結果迭代到數據庫來註冊項目。這應該使您的數據更容易管理,並使您的Java代碼更加簡潔。