简体   繁体   English

如何编写自己的逻辑来使用 Unity 初始化属性?

[英]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:假设您有 Class A 和 Class B。这两个类都有一个私有变量:

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问题:重复init()代码

My Solutions:我的解决方案:

  1. Simple Factory Pattern: create a StoreFactory class with a Init method that will return a Store instance.简单工厂模式:使用将返回 Store 实例的Init方法创建StoreFactory class。
  2. Abstract Factory: Create a Abstract Class that has init() method and let Class A and B inherit from it抽象工厂:创建一个具有 init() 方法的抽象 Class 并让 Class A 和 B 从它继承
  3. ?? ??

Is there a third way to achieve this?有没有第三种方法可以实现这一目标? Perhaps with dependency injection container Unity?也许使用依赖注入容器 Unity? I would also be interested in knowing any other way of achieving this.我也有兴趣知道实现这一目标的任何其他方式。 With or without unity.有或没有统一。

I would avoid the inheritance .我会避免使用inheritance Composing is likely to be easier for maintenance in the long run compared to the inheritance , for this reason i will prefer the factory approach or injecting some service into the classes.从长远来看,与inheritance相比,编写可能更容易维护,因此我更喜欢工厂方法或向类中注入一些服务。

Another approach will be to have the Init method as part of the Store class definition.另一种方法是将Init方法作为Store class 定义的一部分。 And inject the Store class into the constructors of Class A and B ( Unity will take care of the wiring).并将Store class 注入Class AB的构造函数中( Unity将负责接线)。
Then you can call the Init method of the Store instead of relying on injecting the factory in each class where the store will be used.然后,您可以调用StoreInit方法,而不是依赖于在将使用 store 的每个 class 中注入工厂。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM