c++工厂模式与IOC容器搭配使用

 1 #include <string>
 2 #include <map>
 3 #include <memory>
 4 #include <functional>
 5 #include <iostream>
 6 using namespace std;
 7 
 8 template <class T>
 9 class IocContainer {
10 public:
11     IocContainer(void){}
12     ~IocContainer()
13     {
14 
15     }
16     //注册需要创建对象的构造函数,通过一个唯一的标识,以便于以后查找
17     template<class Drived>
18     void RegisterType(string strKey) {
19         std::function<T* ()> function = [] {return new Drived();};
20         RegisterType(strKey, function);
21     }
22 
23     //根据唯一的标识去查找对应的构造函数
24     T* Resolve(string strKey) {
25         if (m_createMap.find(strKey) == m_createMap.end())
26             return nullptr;
27         std::function<T* ()> function = m_createMap[strKey];
28         return function();
29     }
30 
31     //创建智能指针
32     std::shared_ptr<T> ResolveShared(string strKey) {
33         T* ptr = Resolve(strKey);
34         return std::shared_ptr<T>(ptr);
35     }
36 private:
37     void RegisterType(string strKey, std::function<T* ()> creator) {
38         if (m_createMap.find(strKey) != m_createMap.end()) {
39             throw std::invalid_argument("已经存在这个key了");
40         }
41         m_createMap.emplace(strKey, creator);
42     }
43 
44 private:
45     map<string, std::function<T* ()>> m_createMap;
46 };
47 
48 struct ICar {
49     virtual ~ICar(){}
50     virtual void test() const = 0;
51 };
52 
53 struct Bus: ICar
54 {
55     Bus(){}
56     void test()const { std::cout << "Bus::test()"<<endl; }
57 };
58 
59 struct Track :ICar {
60     Track() {};
61     void test() const { std::cout << "Track::test" << endl; }
62 
63 };
64 
65 int main() {
66     IocContainer<ICar> carIOC;
67     carIOC.RegisterType<Bus>("bus");
68     carIOC.RegisterType<Track>("track");
69 
70     std::shared_ptr<ICar> bus = carIOC.ResolveShared("bus");
71     bus->test();
72     std::shared_ptr<ICar> track = carIOC.ResolveShared("track");
73     track->test();
74     system("pause");
75     return 0;
76 }

猜你喜欢

转载自www.cnblogs.com/chenyibin1995/p/11051549.html