软件设计⑦|单例模式
一、单例模式
https://baike.baidu.com/item/%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F/5946627?fr=aladdin
二、代码
(1)效果图
(2)代码
student.h
1 #pragma once 2 #ifndef _SINGLETON_H_ 3 #define _SINGLETON_H_ 4 5 class Student 6 { 7 public: 8 static Student* GetInstance(); 9 protected: 10 Student(); 11 private: 12 static Student* _instance; 13 }; 14 15 #endif
student.cpp
1 #include "student.h" 2 #include <iostream> 3 using namespace std; 4 5 Student* Student::_instance = 0; 6 7 Student::Student() 8 { 9 cout << "create ..." << endl; 10 } 11 12 Student* Student::GetInstance() 13 { 14 if (0 == _instance) 15 { 16 _instance = new Student(); 17 } 18 else 19 { 20 cout << "already exist" << endl; 21 } 22 23 return _instance; 24 } 25 26 int main() 27 { 28 Student* t = Student::GetInstance(); 29 t->GetInstance(); 30 31 return 0; 32 }