1. 概念
If a system only needs one instance of a class, and that instanceneeds to be accessible in many different parts of a system, you control both instantiation and access by making that class a singleton.
两个点:类的唯一实例和需要在多处被访问,这就是singleton模式的精髓。
singleton是最简单的设计模式,其应用意义在于全局保存类的唯一实例。最常见的应用是配置文件,配置文件常常是多个处理线程共用一份配置文件,全局只要存在一份配置文件即可。
2. 实例
小餐馆常常在墙上贴一个大菜单,顾客看下大菜单就能点菜,此处,这个大菜单就可以应用singleton模式,code:
Big_menu.h
#include <iostream> #include "Big_menu.h" Big_menu::Big_menu(void) { } Big_menu::~Big_menu(void) { } Big_menu& Big_menu::instance() { static Big_menu big_menu; return big_menu; } void Big_menu::noodles() { std::cout << "------------------------------------------" << std::endl; std::cout << "-----------红烧牛肉拉面 10元--------------" << std::endl; std::cout << "-----------红烧羊肉拉面 10元--------------" << std::endl; std::cout << "------------------------------------------" << std::endl; }
测试:
#include <iostream> #include "Big_menu.h" using namespace std; int _tmain(int argc, _TCHAR* argv[]) { //Big_menu big_menu; //报错:error C2248: “Big_menu::Big_menu”: 无法访问 private 成员(在“Big_menu”类中声明) Big_menu::instance().noodles(); //work well system("pause"); return 0; }
输出:
------------------------------------------
-----------红烧牛肉拉面 10元------
-----------红烧羊肉拉面 10元------
------------------------------------------
分析:
1)构造函数私有化
通过私有化构造函数,使用户无法直接构造对象
2)静态成员函数instance
静态成员函数与对象无关,通过类名称+域区分符+函数名就能调用静态函数。
3)静态局部变量big_menu
在静态成员函数instance中定义静态局部变量big_menu,静态局部变量仅分配一次内存,函数返回后,该变量不会消失
通过上述3部分组合,使得类实例全局唯一
3. 总结
单件模式在实际项目中大量使用,是必须要掌握的设计模式之一