在C++中實(shí)現(xiàn)依賴注入通常有幾種方式:
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++中實(shí)現(xiàn)依賴注入的一些常用方式,具體的實(shí)現(xiàn)方式可以根據(jù)項(xiàng)目需求和設(shè)計(jì)來(lái)選擇。