单例模式及其C++实现
2016-02-18 15:18
459 查看
单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例的特殊类。通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问,从而方便对实例个数的控制并节约系统资源。如果希望在系统中某个类的对象只能存在一个,单例模式是最好的解决方案。
main函数
//Singleton.h文件
#ifndef _SINGLETON_H #define _SINGLETON_H class Singleton { public: static Singleton * getInstance(); private: Singleton(); Singleton(const Singleton&); const Singleton& operator=(const Singleton&); static Singleton *instance; }; #endif
//Singleton.cpp文件
#include "singleton.h" Singleton::Singleton() { } const Singleton& Singleton::operator=(const Singleton& singleton) { return singleton; } Singleton::Singleton(const Singleton &) { } Singleton* Singleton::instance = new Singleton; Singleton* Singleton::getInstance() { return instance; }
main函数
#include "Singleton.h" #include <stdio.h> int main(){ Singleton* singleton1 = Singleton::getInstance(); Singleton* singleton2 = Singleton::getInstance(); if (singleton1 == singleton2) fprintf(stderr,"singleton1 = singleton2\n"); getchar(); return 0; }
相关文章推荐
- C++Builder 2010深入TObject类
- 单链表的简单应用
- c++ 根据指针类型获取原类型
- VC++的窗口句柄和窗口ID
- Cef概览
- Cef重要概念
- C语言二分查找法
- Cef应用资源布局
- Cef应用程序结构
- 多重继承《C++ primer 3th》
- neuq oj 1034: C基础-求同存异 C++
- [C/C++不常见语法特性]_[初级]_[左值-右值-lvalue-rvalue]
- [C/C++不常见语法特性]_[初级]_[左值-右值-lvalue-rvalue]
- [群150178878]nRF51822学习笔记–硬件外设篇【1】
- C++ vector 自定义类,重载==操作符,使用STL的find查找
- c++变量的作用域、生存期和可见性
- 关于c++虚函数及访问基类私有函数的实践及一些疑问
- C++中 #ifdef 和#endif的作用
- 实现一些简单的单链表
- test