首页 > 代码库 > 单例模式

单例模式

【1】什么是单例模式?

【2】单例模式的代码示例:

示例代码:

 1 #include <iostream> 2 #include <string> 3 using namespace std; 4  5 class Singleton 6 {     7 private: 8     int i; 9     static Singleton *instance;10     Singleton(int i)11     {12         this->i = i;13     }14 public:15     static Singleton *getInstance()16     {17         return instance;18     }19     void show()20     { 21         cout << i << endl;22     }23 };24 25 Singleton* Singleton::instance = new Singleton(8899); 26 27 class A : public Singleton28 {29 30 };31 32 int main()33 {34     Singleton *s = Singleton::getInstance();35     Singleton *s2 = A::getInstance();36     cout << s << endl;37     cout << s2 << endl;38     cout << (s == s2) << endl;39     return 0;40 }
View Code

 

Good   Good  Study,  Day  Day  Up.

顺序  选择  循环  总结

单例模式