【问题标题】:How to write own logic to initialize a property with Unity?如何编写自己的逻辑来使用 Unity 初始化属性?
【发布时间】:2019-11-19 11:39:11
【问题描述】:

假设您有 A 类和 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
 }
}

问题:重复 init() 代码

我的解决方案:

  1. 简单工厂模式:使用Init 方法创建一个StoreFactory 类,该方法将返回一个Store 实例。
  2. 抽象工厂:创建一个具有init()方法的抽象类,让A类和B类继承它
  3. ??

有没有第三种方法来实现这一点?也许使用依赖注入容器 Unity? 我也有兴趣了解实现这一目标的任何其他方式。有或没有统一。

【问题讨论】:

    标签: c# .net api design-patterns unity-container


    【解决方案1】:

    我会避免继承。从长远来看,组合可能比继承更容易维护,因此我更喜欢工厂方法或向类中注入一些服务。

    另一种方法是将Init 方法作为Store 类定义的一部分。并将Store 类注入Class AB 的构造函数中(Unity 将负责接线)。
    然后你可以调用StoreInit 方法,而不是依赖于在将要使用store 的每个类中注入工厂。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-17
      • 1970-01-01
      • 2013-04-03
      • 2018-11-18
      • 2018-09-18
      • 1970-01-01
      • 2011-11-18
      • 1970-01-01
      相关资源
      最近更新 更多