主要是看着http://www.mscenter.edu.cn/blog/k_eckel 学习,有代码并且23种设计模式总结的很好~
我自己简单记点笔记。
设计模式:用一个通用模式可以解决一类问题,一个框架
一创建型模式:
Factory, AbstractFactory,Singleton,Builder,Prototype
这里面试测试岗位最常问到要求写的就是singleton单例设计模式,C++primer Plus中也有提到
所谓单例设计模式,是想定义一个只能被实例化一次的类, 这个具体化后的对象相当于是面向对象编程中的一个全局变量(全局变量不符合面向对象编程的要求)。
实现:将构造函数放在protected或private中,使得外部不能利用construct构造对象。唯一的途径是利用public static的成员函数调用保护的构造成员函数,但static成员函数保证了只能执行一次,生成一个唯一的类对象。
code:
1 1 #ifndef SINGLETON__H_INCLUDED 2 2 #define SINGLETON__H_INCLUDED 3 3 #include <iostream> 4 4 5 5 /*Singleton 单例设计模式,构造函数放在private或protected中 6 6 通过public的静态成员函数调用construct,static函数只在第一次调用时执行,所以单例模式 7 7 只生成一个实例*/ 8 8 9 9 using namespace std; 10 10 class Singleton 11 11 { 12 12 public: 13 13 static Singleton* Instance(); 14 14 protected: 15 15 Singleton(); 16 16 private: 17 17 static Singleton *_instance; 18 18 }; 19 19 20 20 #endif // SINGLETON__H_INCLUDED 21 21 //------------------------------------------------------------------ 22 22 #include "Singleton.h" 23 23 #include <iostream> 24 24 25 25 using namespace std; 26 26 27 27 Singleton * Singleton::_instance=0; // 28 28 29 29 Singleton::Singleton() 30 30 { 31 31 cout<<"Singleton"<<endl; 32 32 } 33 33 34 34 Singleton* Singleton::Instance() 35 35 { 36 36 if(_instance==0) 37 37 { 38 38 _instance=new Singleton(); 39 39 } 40 40 return _instance; 41 41 } 42 42 //--------------------------------------------------------- 43 43 #include <iostream> 44 44 #include "Singleton.h" 45 45 using namespace std; 46 46 47 47 int main() 48 48 { 49 49 Singleton* sgn=Singleton::Instance();// public 50 50 51 51 return 0; 52 52 }