问题描述
我不知道什么是C ++使用依赖注入的方式?是使用模板还是多态类?考虑下面的代码,
I wonder what is the C++ way of using dependency injection? Is that using templates or polymorphic classes? Consider the following code,
class AbstractReader
{
public:
virtual void Read() = 0;
};
class XMLReader : public AbstractReader
{
public:
void Read() { std::cout << "Reading with a XML reader" << std::endl; }
};
class TextFileReader : public AbstractReader
{
public:
void Read() { std::cout << "Reading with a Text file reader" << std::endl; }
};
class Parser
{
public:
Parser(AbstractReader* p_reader) : reader(p_reader) { }
void StartParsing() { reader->Read();
// other parsing logic
}
private:
AbstractReader* reader;
};
template<class T>
class GenericParser
{
public:
GenericParser(T* p_reader) : reader(p_reader) { }
void StartParsing()
{
reader->Read();
}
private:
T* reader;
};
1 - 这是最好的方法? 或解析器 ?我知道如果是GenericParser ,继承可以删除。
1 - Which is the best method? GenericParser or Parser? I know if it is GenericParser, inheritance can be removed.
2 - 如果模板是可行的,是否可以将所有代码写入头文件?我看到许多类使用模板写头文件中的所有代码,而不是.h / .cpp组合。
2 - If templates is the way to go, is it OK to write all the code in header files? I have seen many classes using templates writes all the code in header files rather than .h/.cpp combination. Is there any problems in doing so, something like inlining etc?
有什么想法吗?
推荐答案
根据您想要如何构建代码或头文件,您没有自由选择。
You don't have a free choice in this, based on how you want to structure your code or header files. The answer is dictated to you by the requirements of your application.
这取决于耦合是否可以在编译时决定,或必须延迟到运行时
It depends on whether the coupling can be be decided at compile time or must be delayed until runtime.
如果组件及其依赖关系之间的耦合在编译时永久决定,则可以使用模板。
If the coupling between a component and its dependencies is decided permanently at compile time, you can use templates. The compiler will then be able to perform inlining.
然而,如果耦合需要在运行时决定(例如,用户选择哪个其他组件将提供依赖,可能通过配置文件),那么您不能使用模板,并且必须使用运行时多态机制。如果是,您的选择包括虚函数,函数指针或 std :: tr1 :: function
。
If however the coupling needs to be decided at runtime (e.g. the user chooses which other component will supply the dependency, perhaps through a configuration file) then you can't use templates for that, and you must use a runtime polymorphic mechanism. If so, your choices include virtual functions, function pointers or std::tr1::function
.
这篇关于C ++依赖注入方式 - 模板或虚拟方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!