【发布时间】:2010-11-10 10:55:23
【问题描述】:
我正在使用 TDD 在 C++ 中编程,它建议在创建对象时使用控制反转(在创建某个类的对象时,将构造的对象传递给它的构造函数)。这很好,但是如何创建构造函数所需的对象?
现在,我正在使用一个工厂(我可以很容易地为我的单元测试更改它),它返回一个指向创建对象的 shared_ptr。 这是正确的方法,还是有更好的方法?
非常简化的示例演示了我在做什么:
#include <iostream>
struct A {
virtual ~A() { }
virtual void foo() = 0;
};
struct B : A {
virtual ~B() { }
virtual void foo() { std::cout<<"B::foo()"<<std::endl; }
};
struct C {
C( A *a ) : a(a) { }
void DoSomething() { a->foo(); }
A *a;
};
int main() {
C c( new B );
c.DoSomething();
}
反对:
#include <iostream>
struct A {
virtual ~A() { }
virtual void foo() = 0;
};
struct B : A {
virtual ~B() { }
virtual void foo() { std::cout<<"B::foo()"<<std::endl; }
};
struct C {
C() : a() { }
void DoSomething() { a.foo(); }
B a;
};
int main() {
C c; // the object of type B is constructed in the constructor
c.DoSomething();
}
EDIT1
This link 解释了 Java 的 IoC,但您可能知道,在 java 中您可以这样做:
class B
{
};
class A
{
public:
A( B b )
...
};
...
A objA( new B ); // this doesn't work in c++
...
【问题讨论】:
-
控制反转概念的任何链接
标签: c++ unit-testing tdd inversion-of-control