在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++中實現依賴注入的一些常用方式,具體的實現方式可以根據項目需求和設計來選擇。