C+中的依赖注入+; 如何在C++中实现依赖注入,而不使用框架或反射?< /P>
我可以使用工厂返回自动或共享的ptr。这是一种很好的方法吗?AFAIK依赖项注入只是意味着,有一个接口到另一个组件所需的组件C+中的依赖注入+; 如何在C++中实现依赖注入,而不使用框架或反射?< /P>,c++,refactoring,dependency-injection,C++,Refactoring,Dependency Injection,我可以使用工厂返回自动或共享的ptr。这是一种很好的方法吗?AFAIK依赖项注入只是意味着,有一个接口到另一个组件所需的组件 namespace ifc { struct service { virtual ~service() {} virtual do_stuff(/*..*/) = 0; }; } // ns ifc class ServiceProviderA : public ifc::service { public; do_stuff(/*.
namespace ifc {
struct service {
virtual ~service() {}
virtual do_stuff(/*..*/) = 0;
};
} // ns ifc
class ServiceProviderA : public ifc::service
{
public;
do_stuff(/*..*/) { /*...*/ }
};
class ServiceProviderB : public ifc::service {/*...*/};
class Client
{
public;
client(ifc::service*);
private:
ifc::service* m_service;
};
我只能猜测,但你的问题是如何管理注入对象的生命周期吗?只需使用共享的ptr来提供所需的服务,并为其设置一个setter即可。例如:
class Engine;
class Car {
public:
void setEngine(shared_ptr<Engine> p_engine) {
this->m_engine = p_engine;
}
int onAcceleratorPedalStep(int p_gas_pedal_pressure) {
this->m_engine->setFuelValveIntake(p_gas_pedal_pressure);
int torque = this->m_engine->getTorque();
int speed = ... //math to get the car speed from the engine torque
return speed;
}
protected:
shared_ptr<Engine> m_engine;
}
// (now must create an engine and use setEngine when constructing a Car on a factory)
类引擎;
班车{
公众:
无效设置引擎(共享\u ptr p\u引擎){
此->m_引擎=p_引擎;
}
油门踏板踏板内侧(油门踏板内侧压力){
此->m_发动机->设置燃油阀输入(p_燃气踏板压力);
int torque=this->m_engine->getTorque();
int speed=…//通过发动机扭矩计算车速的数学方法
返回速度;
}
受保护的:
共享_ptr m_引擎;
}
//(现在,在工厂制造汽车时,必须创建发动机并使用setEngine)
避免使用auto_ptr,因为您不能通过多个对象共享它(分配时它会转移所有权)。假设注入对象的所有权转移到从属对象如何。这将解决组合避免使用智能指针的生存期问题。但是,对于所有权很重要的复杂情况,智能指针将是选择
class Car {
public:
Car(IEngine *pEngine) {
m_pEngine = pEngine;
}
...
~Car()
{
delete m_engine;
}
protected:
IEngine *m_pEngine;
}
对于dependet肯定比注入对象的生存期短的情况,最好将注入对象作为引用传递。这将清楚地表明注入对象不是由DeDeNtt对象拥有。我们不在C++中使用那些流行词。代码非常接近这个问题。是的,问题是如何管理注入对象的生命周期。这听起来非常合理。这样做仅仅是为了使代码可测试,还是有更好的替代方案?没关系,您不会损失太多性能,您的代码将更加灵活和可测试!