4
A
回答
4
只需使用一个shared_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)
避免使用auto_ptr,因为您无法通过多个对象(它在分配时转移所有权)共享它。
1
AFAIK依赖注入只是意味着有一个到另一个组件所需的组件的接口。
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;
};
我只能猜测,但你的问题是如何管理注入的对象的生命周期?
+0
您的代码非常接近问题。是的,问题是如何管理注入对象的生命周期。 – frast 2009-06-29 21:48:18
0
假设注入对象的所有权转移给依赖对象,这种情况如何?这将解决避免使用智能指针的构图的生存期问题。但是,对于拥有所有权的复杂情况,智能指针将成为选择。
class Car {
public:
Car(IEngine *pEngine) {
m_pEngine = pEngine;
}
...
~Car()
{
delete m_engine;
}
protected:
IEngine *m_pEngine;
}
对于其中dependet是肯定有少寿命比所注入的对象,它能够更好地通过注入对象为基准的情况下。这将清楚地表明注入的对象不属于dependet对象。
相关问题
- 1. C#依赖注入
- 2. C#依赖注入 - 如何注入无源的依赖关系?
- 3. C#依赖注入框架
- 4. C#依赖注入问题
- 5. C#依赖注入样品
- 6. C#类依赖注入
- 7. C#Web API中的依赖注入
- 8. 依赖注入
- 9. 依赖注入
- 10. 依赖注入
- 11. 依赖注入
- 12. 依赖注入
- 13. 依赖注入
- 14. 使用依赖注入来注入依赖注入器
- 15. BroadcastReceiver中的依赖注入
- 16. MethodInterceptor中的依赖注入
- 17. backbone.js中的依赖注入
- 18. Django中的依赖注入
- 19. Arduino中的依赖注入
- 20. PHP中的依赖注入
- 21. Guice中的依赖注入
- 22. ZF2中的依赖注入
- 23. Laravel中的依赖注入
- 24. Symfony中的依赖注入
- 25. @EJB中的依赖注入
- 26. Typedefs,C++/CLI,C#+依赖注入
- 27. 结构图的C#依赖注入
- 28. 依赖注入Android
- 29. MVP依赖注入
- 30. NServiceBus依赖注入
我们不会在C++中做那些流行语。 – 2009-06-29 21:33:54
对你有好处,尼尔! ^^ – 2009-06-29 21:37:58