2013-04-27 52 views
2

我正在創建一個塔防遊戲。在創建關卡之前,我需要在內存中準備好關於怪物,塔臺等的統計信息。例如:確保許多類的數據初始化的設計模式

fastmonster.name = "Rabbit"; 
fastmonster.health = 100; 
fastmonster.speed = 10; 
slowmonster.name = "Turtle"; 
slowmonster.health = 500; 
slowmonster.speed = 2; 

塔和其他東西也是如此。

(我還沒有決定如何將詳細的文件進行讀取。)

如何確保所有數據已準備就緒怪物或塔式類的對象之前創建?我正在尋找一種設計模式,它允許我全局初始化所有數據,並允許我使用常規構造函數創建怪物對象。同時它應該確保在讀取單位統計數據之前不會創建任何對象。

我相信這個問題已經解決了一百萬次,但到目前爲止,我沒有發現真正適合這個問題,是不是一個超級複雜的幾個抽象水平的任何解決方案。

我的解決方案至今

我所做的構造私人和定義一個create()功能,看起來像這樣

Monster Monster::create (MonsterType type) { 
    if (!initialized()) { 
     initialize(); 
     initialized = true; 
    } 
    return new Monster(type); 
} 

的問題是,現在我需要創建塔同樣的功能和所有其他遊戲元素。這看起來像很多重複。

又一想

我把所有的構造私有。創建一個(singleton?)工廠類並使其成爲所有類的朋友,並讓它創建所有對象。工廠在創建時會進行初始化。

GOF模式

我看着其他創建模式,但他們都不適合。或者我只是不夠了解他們。

+0

語言是C++,我假設? – 2013-04-27 11:30:23

+0

是的,C++與Qt。但是我故意忽略它,假設解決方案是語言不可知的。 – problemofficer 2013-04-27 11:31:42

+0

我會去工廠做一個數據驅動的創建,使其具有通用性(避免爲每個類引入特定的代碼)。 – asermax 2013-04-28 23:13:28

回答

0

我認爲你的解決方案很棒。

您可以通過使用模板方法來改善它GOF模式,以避免重複。

不幸的是,我不知道它在C++中如何實現,但在C#中它可能是以下幾點:

public abstract class BaseEntity<T> 
{ 
    private bool initialized = false; 

    public BaseEntity<T> Create(T typeOfEntity) 
    { 
     if (!Initialized()) 
     { 
      Initialize(); 
      initialized = true; 
     } 

     return GetEntity(typeOfEntity); 
    } 

    protected abstract void Initialize(); 
    protected abstract bool Initialized(); 
    protected abstract BaseEntity<T> GetEntity(T typeOfEntity); 
} 

public class MonsterEntity:BaseEntity<MonsterType> 
{ 
    //... 

    public MonsterEntity(MonsterType typeOfEntity) 
    { 
     //... 
    } 

    protected override void Initialize() 
    { 
     //initialize logic 
    } 

    protected override bool Initialized() 
    { 
     bool initialized = false; 

     //check for initialization 

     return initialized; 
    } 

    protected override BaseEntity<MonsterType> GetEntity(MonsterType typeOfEntity) 
    { 
     return new MonsterEntity(typeOfEntity); 
    } 

    //... 
} 

你也可以爲你的entites添加亞型,使方法GetEntity的織物的方法。