I’ve have a library of data access objects and am tasked with designing the logic layer. In this layer, I have access to the core data model, which I need to use to create Profile objects that can be passed to the UI for rendering.
Every object in the data model that needs an equivalent Profile object derives from the type Page. So ideally I need to write one method that accepts a Page as a parameter and returns a Profile. It’s not quite as simple as this, however, because the Profile objects are split into groups of Apps, which the user can enable.
I’ve tried various different approaches (and keep on deleting the whole lot and starting again!), but here’s the solution I’m trying at the moment:
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;
}
}
I have to create 24 fairly big Profile classes for different pages, so I just want to make sure I’m doing it the best way I can before I start coding away. As you can see this design has a few flaws, but is there a better way of doing this? Has anyone tried a similar thing before (this situation can’t be that rare, can it)?
Have a look at this Factoy PAttern (source):
Then two App might have the same type of Object, your implementation of the creation of the object will be done only once.
If you need further details, please ask.