dimanche 7 juillet 2019

Pattern to create new object with type that depends on the type of another object?

I have something like this:

interface IProduct { }

class ProductA : IProduct { }

class ProductB : IProduct { }

....

interface IViewModel { }

class ProductAViewModel : IViewModel { }

class ProductBViewModel : IViewModel { }


And now I want to be able to create instances of my ViewModels without knowing real type of products:

IProduct prod = new ProductA();
IViewModel vm = someFactoryOrBuilderObject.CreateViewModel(prod);
// real type of vm depends on the product's type
// if prod is ProductA, vm must be ProductAViewModel
...
DisplayViewModel(vm); // working with vm as IViewModel (regardless of it's real type)

Goals:

  • Type of viewmodel must be resolved at runtime.

  • Adding of new products and viewmodels to my app should NOT require any changes to the existing code.

Which is the best way to implement this functionality? There are some obvious ways, but they are not satisfying:

  • Creating something like map (dictionary) of types (productType<->vmType). But when I'd want to add some more products, I will have to change this map.
  • Creating a factory method like GetViewModel() inside every product class. But this insanely violates SOLID's SRP.
  • Creating a Factory or Builder. But these patterns don't cover my requirements.

Aucun commentaire:

Enregistrer un commentaire