In a generic class I have to create a new object of the same type:
public abstract class ViewModel<TPrimaryModel>
{
public void DoSomething()
{
...
ViewModel<TPrimaryModel> newViewModel = new TPrimaryModel(someArguments);
}
}
Doing this isn't supported by C#. So I decided to introduce a CreateInstance
-method:
public abstract class ViewModel<TPrimaryModel>
{
public void DoSomething()
{
...
ViewModel<TPrimaryModel> newViewModel = CreateInstance(someArguments);
}
protected abstract ViewModel<TPrimaryModel> CreateInstance(Object someArguments);
}
public class UserViewModel : ViewModel<User>
{
public UserViewModel(Object someArguments)
{
...
}
protected override ViewModel<TPrimaryModel> CreateInstance(Object someArguments)
{
return new UserViewModel(someArguments);
}
}
Unfortunately the parameters which have to be passed to the constructor or CreateInstance
method depend on the ViewModel itself. Some need more arguments, some need lees. So this construct isn't flexible enough. Example: ViewModelA viewModelA = new ViewModelA(serviceA, 5, "ViewModelA");
ViewModelB viewModelB = new ViewModelB(serviceB, serviceA, 6, "ViewModelB");
I wonder what's the right way to go. Encapsulate the arguments for object creation? Factory pattern? Or should I avoid inheritance in that situation and stick to composition?
Aucun commentaire:
Enregistrer un commentaire