1 #include<iostream>
2 #include<string>
3
4 using namespace std;
5
6 class Singleton{
7
8 public:
9 Singleton(){}
10 Singleton( const Singleton& ){}
11 ~Singleton(){}
12
13 public:
14 static bool CreateSingleton( void );
15 static void ReleaseSingleton( void );
16 static Singleton& GetInstance();
17 static Singleton* GetInstancePrt();
18
19 public:
20 string& GetName()
21 {
22 return m_strName;
23 }
24
25 void SetName( const string& strName )
26 {
27 m_strName = strName;
28 }
29
30 void Say( void )
31 {
32 cout << "This is " << m_strName ;
33 cout << ".And My address is :" << this << endl;
34 }
35
36 private:
37 static Singleton * m_pSingleton;
38 string m_strName;
39 };
40
41 Singleton *Singleton::m_pSingleton = NULL;
42
43 bool Singleton::CreateSingleton()
44 {
45 assert( !m_pSingleton );
46 m_pSingleton = new Singleton();
47 return ( NULL != m_pSingleton );
48 }
49
50 void Singleton::ReleaseSingleton()
51 {
52 if( m_pSingleton )
53 delete m_pSingleton;
54 }
55
56 Singleton& Singleton::GetInstance()
57 {
58 assert( m_pSingleton );
59 return ( *m_pSingleton );
60 }
61
62 Singleton* Singleton::GetInstancePrt()
63 {
64 assert( m_pSingleton );
65 return m_pSingleton;
66 }
67
68 void TestFuncA()
69 {
70 Singleton::GetInstance().SetName("TestFunction A");
71 }
72
73 void TestFuncB()
74 {
75 Singleton::GetInstance().SetName("TestFunction B");
76 }
77
78 void SaySomething()
79 {
80 Singleton::GetInstance().Say();
81 }
82
83 int main()
84 {
85 Singleton::CreateSingleton();
86
87 Singleton* pSingleton = Singleton::GetInstancePrt();
88
89 if( !pSingleton )
90 {
91 cout << "Create Singleton failed!" << endl;
92 }
93 else
94 {
95 cout << "Create Singleton Successfully!" << endl;
96 TestFuncA();
97 SaySomething();
98 TestFuncB();
99 SaySomething();
100 }
101
102 Singleton::ReleaseSingleton();
103
104
105
106 getchar();
107
108 return 0;
109 }