2009-06-29 128 views
4

如何在不使用框架或反射的情況下明確實現C++中的依賴注入?C++中的依賴注入

我可以使用工廠來返回auto_ptr或shared_ptr。這是做這件事的好方法嗎?

+3

我們不會在C++中做那些流行語。 – 2009-06-29 21:33:54

+0

對你有好處,尼爾! ^^ – 2009-06-29 21:37:58

回答

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對象。