2012-02-20 121 views
0

在我的遊戲項目中,我使用的是MVC方案。模型和視圖完全分離。觀察由觀察者模式驅動。所以當遊戲實體發生某些事情時(創建,銷燬,更新...),視圖將通過監聽器通知。當分配模型中的新實體時,我需要創建適當的視圖模型(EntityMesh)。C++ MVC模型viewmodel「翻譯」和繼承

  • EntityMesh是基礎視圖模型
  • 遊戲::實體是模型

這個例子模型派生樹基地看起來是這樣的:

  • 遊戲::實體 - > Game :: PhysicalEntity - > Game :: PhysicalGridEntity
  • Game :: Entity - > Game :: ActorEntity - > Game :: FreeActorEntity

這就是我目前「解決」這個問題的方法......但是在將來我期待30個以上的Game :: Entity和EntityMesh的衍生物。這是非常醜陋的非OOP設計。

EntityMesh* WorldView::_translate(Game::Entity* const ent) 
{ 
    //TODO: finish translator... 
    std::cout << "TRANSLATING!: " << typeid(ent).name() << std::endl; 

    Game::PhysicalGridEntity* pgent = dynamic_cast<Game::PhysicalGridEntity*>(ent); 
    if(pgent) 
    { 
     std::cout << "CREATING: PhysicalGridEntity" << std::endl; 
     return new PhysicalGridEntityMesh(this, pgent); 
    } 
    else 
    { 
     Game::PhysicalEntity* pent = dynamic_cast<Game::PhysicalEntity*>(ent); 
     if(pent) 
     { 
      std::cout << "CREATING: PhysicalEntity" << std::endl; 
      return new PhysicalEntityMesh(this, pent); 
     } 
     else 
     { 
      Game::FreeActorEntity* faent = dynamic_cast<Game::FreeActorEntity*>(ent); 
      if(faent) 
      { 
       std::cout << "CREATING: FreeActorEntity" << std::endl; 
       return new FreeActorEntityMesh(this, faent); 
      } 
     } 
    } 

    return NULL; 
}; 

任何想法如何使這更清晰和更多的面向對象不混合視圖和模型?

編輯:任何暗示使用什麼模式將幫助:)

+1

如何使用訪問者模式? – 2012-02-20 14:13:26

回答

2

首先,你沒有一個控制器組件。你在哪裏連接模型和視圖的業務邏輯?其次,我不確定你想要做什麼,但可能工廠/訪客模式會幫助你。

+0

我沒有提到控制器,因爲它與這個問題沒有任何關係。這些ifs只是一個例子,我目前正在處理這個問題。工廠/訪問者模式這可能會工作... – BlackCat 2012-02-20 14:17:26

+1

我第二個BlackCat在這裏,工廠/訪問者似乎適當。 – qdii 2012-02-20 14:19:29