mardi 19 novembre 2019

How to write own logic to initialize a property with Unity?

Let's suppose you have Class A and Class B. Both these classes have a private variable:

private Store _store {get;set}

class Class A
{
 private Store _store {get;set}
 constructor()
 {
  init(param1,param2,..);
 }
 init(param1,param2,..)
 {
  //logic to initialize _store
 }
}

class Class B
{
 private Store _store {get;set}
 constructor()
 {
  init(param1,param2,..);
 }
 init(param1,param2,..)
 {
  //logic to initialize _store
 }
}

Problem: duplicate init() code

My Solutions:

  1. Simple Factory Pattern: create a StoreFactory class with a Init method that will return a Store instance.
  2. Abstract Factory: Create a Abstract Class that has init() method and let Class A and B inherit from it
  3. ??

Is there a third way to achieve this? Perhaps with dependency injection container Unity? I would also be interested in knowing any other way of achieving this. With or without unity.

Aucun commentaire:

Enregistrer un commentaire