如何在不使用框架或反射的情况下在 C++ 中显式实现依赖注入(inject)?
我可以使用工厂返回 auto_ptr 或 shared_ptr。这是一个好的方法吗?
最佳答案
只需将 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,因为您不能通过多个对象共享它(它会在分配时转移所有权)。
关于c++ - C++ 中的依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1060483/