依赖注入和控制反转
如果对象A想要调用B,一定要newB。这样A和B就紧密的耦合
采用工厂方法模式,有个IOC容器的概念,A想要用B的方法,先告诉IOC,通过IOC注入A对象。使得A和B进行松耦合。
为什么需要IOC而不是直接new呢?如果有大量的对象,都通过new来生成,但是可能会存在互相引用,导致重叠的调用,就会十分的混乱。IOC用来管理这些对象,类似于点名册,这样只需要去IOC里面去找,就可以调用相应需要的对象。
#include <string>
#include <map>
#include <memory>
#include <functional>
#include <iostream>
#include <vector>
#include <any>
#include <unordered_map>
//#include "NonCopyable.hpp"
class IocContainer
{
std::unordered_map<std::string, std::any> m_creatorMap;
private:
void RegisterType(const std::string &strKey, std::any constructor)
{
if (m_creatorMap.find(strKey) != m_creatorMap.end())
{
throw std::invalid_argument("this key has already exist");
}
m_creatorMap.emplace(strKey, constructor);
}
public:
IocContainer() {}
~IocContainer() {}
template<class T, class Depend, class ...Args>
void RegisterType(const std::string& strKey)
{
std::function<T*(Args...)> function = [](Args... args) { return new T(new Depend(args...)); };
RegisterType(strKey, function);
}
template<class T, class ...Args>
T* Resolve(const std::string& strKey, Args... args)
{
if (m_creatorMap.find(strKey) == m_creatorMap.end())
{
return nullptr;
}
std::any resolver = m_creatorMap[strKey];
std::function<T*(Args...)> function = std::any_cast<std::function<T*(Args...)>>(resolver);
return function(args...);
}
//创建智能指针对象
template<class T, class ...Args>
std::shared_ptr<T> ResolveShared(const std::string& strKey, Args... args)
{
T* ptr = Resolve<T>(strKey, args...);
return std::shared_ptr<T>(ptr);
}
};
struct Base
{
virtual void Func() {}
virtual ~Base() {}
};
struct DerivedB :public Base
{
DerivedB(int a, double b) :m_a(a), m_b(b)
{
}
void Func() override
{
std::cout << m_a + m_b << std::endl;
}
private:
int m_a;
double m_b;
};
struct DerivedC :Base
{
void Func() override
{
std::cout << "call func in DerivedC" << std::endl;
}
};
struct A
{
A(Base *ptr) :m_ptr(ptr) {}
void Func()
{
m_ptr->Func();
}
~A()
{
if (m_ptr != nullptr)
{
delete m_ptr;
m_ptr = nullptr;
}
}
private:
Base *m_ptr;
};
void TestIoC()
{
IocContainer ioc;
ioc.RegisterType<A, DerivedB, int, double>("B");
auto b = ioc.ResolveShared<A>("B", 1, 2.0);
ioc.RegisterType<A, DerivedC>("C");
auto c = ioc.ResolveShared<A>("C");
b->Func();
c->Func();
}
int main()
{
TestIoC();
return 0;
}