在C++中实现依赖注入通常有几种方式:
class Dependency {
// Dependency implementation
};
class MyClass {
public:
MyClass(Dependency* dependency) : dependency_(dependency) {}
private:
Dependency* dependency_;
};
class Dependency {
// Dependency implementation
};
class MyClass {
public:
void setDependency(Dependency* dependency) {
dependency_ = dependency;
}
private:
Dependency* dependency_;
};
class DependencyInterface {
public:
virtual void doSomething() = 0;
};
class Dependency : public DependencyInterface {
void doSomething() override {
// Dependency implementation
}
};
class MyClass {
public:
MyClass(DependencyInterface* dependency) : dependency_(dependency) {}
private:
DependencyInterface* dependency_;
};
这些是C++中实现依赖注入的一些常用方式,具体的实现方式可以根据项目需求和设计来选择。