我正在练习依赖注入,有几个问题我不知道如何处理。
发布于 2014-03-26 07:36:57
所有的个人意见,但我们要走了。
1)将依赖项传递给构造函数。如果存在合理的默认值,则提供多个构造函数或使用默认参数。
2)如果您要经常使用同一组依赖项,您可以通过创建一个“依赖集”类来保存一些类型,该类的实例可以传递给构造函数,如下所示:
struct Iface1;
struct Iface2; // Dependent interfaces
struct Iface3;
struct DependencySet
{
Iface1& iface1;
Iface2& iface2;
Iface3& iface3;
};
class Dependent
{
public:
Dependent(DependencySet& set)
: iface1(set.iface1)
, iface2(set.iface2)
, iface3(set.iface3)
{}
private:
Iface1& iface1;
Iface2& iface2;
Iface3& iface3;
};3)就我个人而言,我倾向于像上面那样使用引用并管理生命周期,这样依赖关系就会超过依赖类,但是如果您想要“忘记”一旦使用了依赖项,就可以使用共享指针。
https://stackoverflow.com/questions/22653907
复制相似问题