公司软件需要一个配置文件,给配置文件信息可能需要被多个类调用,因此便想到了单例模式实现该类。

单例模式也称为单件模式、单子模式,可能是使用最广泛的设计模式。其意图是保证一个类仅有一个实例,并提供一个访问它的全局访问点,该实例被所有程序模块共享。

示例:

 1 #include<memory>
 2 #include <string>
 3 #include<iostream>
 4 
 5 using namespace std;
 6 
 7 class CSingleton
 8 {
 9 public:
10     CSingleton(){};
11     virtual ~CSingleton(){};
12 
13     static shared_ptr<CSingleton> getOject(){ return mSingleton; };
14     string getFileName() const{ return mFileName; };
15     void setFileName(const string& pFileName){ mFileName = pFileName; };
16 
17 private:
18     CSingleton(const CSingleton& pSingleton){};
19     CSingleton &operator=(const CSingleton& pSingleton){};
20 
21 private:
22     static shared_ptr<CSingleton> mSingleton;
23     string mFileName;
24 };
25 
26 shared_ptr<CSingleton> CSingleton::mSingleton = make_shared<CSingleton>();
27 
28 class CTestA
29 {
30 public:
31     CTestA(){};
32     virtual ~CTestA(){};
33     void Show() const
34     {
35         shared_ptr<CSingleton> pSingle = CSingleton::getOject();
36         cout << pSingle->getFileName() << endl;
37     }
38 };
39 
40 int main()
41 {
42     string strFileName = "Test.rule";
43     shared_ptr<CSingleton> pSingle = CSingleton::getOject();
44     pSingle->setFileName(strFileName);
45 
46     CTestA* pTestA = new CTestA();
47     pTestA->Show();
48     delete pTestA;
49     pTestA = nullptr;
50     system("pause");
51     return 0;
52 }

 

posted on 2017-03-10 14:50  barbielxt  阅读(107)  评论(0)    收藏  举报