2011-07-26 62 views
1

我有一個數據訪問對象庫,負責設計邏輯層。在此圖層中,我可以訪問核心數據模型,我需要使用該模型創建可以傳遞給用戶界面進行渲染的對象Profile根據封裝對象的類型初始化派生類

數據模型中需要對應的Profile對象的每個對象都來自Page類型。所以理想情況下,我需要編寫一個方法來接受一個Page作爲參數並返回一個Profile。然而,這並不是那麼簡單,因爲Profile對象被分成多組應用程序,用戶可以啓用它們。

我已經嘗試了各種不同的方法(和繼續刪除一大堆並重新開始!),但在這裏我想此刻的解決方案:

public interface IApp 
{ 
    //should be static, but interfaces cannot define static properties 
    //so this instance property will return a private static field 
    Dictionary<Type, IProfileCreator> Profiles { get; } 

    //other things the App contains that isn't relevant to the profiles 
} 

public interface IProfile 
{ 
    Page page { get; set; } 
} 

public interface IProfileCreator 
{ 
    IProfile Create(Page page); 
} 

public class ProfileCreator<TProfile> where TProfile : IProfile, new() 
{ 
    IProfile IProfileCreator.Create(Page page) 
    { 
     return Create(page); 
    } 

    public TProfile Create(Page page) 
    { 
     //constructor will have to be blank because of the new() constraint 
     TProfile profile = new TProfile(); 
     profile.Page = page; 
     return profile; 
    } 
} 

我得相當創建24大Profile不同頁面的類,所以我只想確保我在開始編碼之前以最好的方式做到這一點。正如你可以看到這個設計有一些缺陷,但是有沒有更好的方法來做到這一點?有沒有人嘗試過類似的東西(這種情況不可能是罕見的,可以)?

回答

2

看一看這個Factoy模式(source):

abstract class ProfileFactory 
    { 
     public abstract IProfile GetProfile(Page p); //Factory Method Declaration 
    } 

class concreteFactoryforProfile1 : ProfileFactory 
    { 
    public override IProfile GetProfile(Page p) //Factory Method Implementation 
      { 
       //data access stuff... 
       return new Profile() { Page = p }; 
      } 
    } 

class concreteFactoryforProfile2 : ProfileFactory 
    { 
    public override IProfile GetProfile(Page p) //Factory Method Implementation 
      { 
       //other data access stuff... 
       return new Profile() { Page = p }; 
      } 
    } 


interface IProfile 
    { 
     Page Page { get; set; } 
     //other properties can come here 
    } 

class Profile : IProfile 
    { 
     public Page Page { get; set; } 
     //other properties can come here 
    } 


public class Test 
{ 
    void Main() 
    { 

     ProfileFactory[] objFactories = new ProfileFactory[2]; 
     objFactories[0] = new concreteFactoryforProfile1(); 
     objFactories[1] = new concreteFactoryforProfile2(); 
     foreach (ProfileFactory objFactory in objFactories) 
     { 
      IProfile objProfile = objFactory.GetProfile(this.Page); 
      Page p = objProfile.Page; 
     } 
    } 
} 

然後兩個表觀可能具有同一類型的對象,您創建對象的實施將只進行一次。

如果您需要更多詳細信息,請詢問。

+0

謝謝你的回答。雖然我很困惑。你可以在'Main()'方法中擴展一下你的示例用法嗎? – Connell

+0

我不知道要添加什麼,它完全取決於您的應用使用他們的配置文件的方式。這裏的事情是使用一個工廠,因爲某個類的實例太複雜了。 – Arthis

+0

這只是twigged ..爲什麼我沒有看到這3小時前?!事實上,我爲什麼沒有想到這一點呢?!謝謝 – Connell