单例模式的几种实现及其比较
来源:互联网 发布:大麦盒子怎么设置网络 编辑:程序博客网 时间:2024/05/21 09:17
1.惰性实现
class Singleton{ static Singleton singletonM; int i; Singleton(int x):i(x){} Singleton& operator=(Singleton&); Singleton(const Singleton&);public: static Singleton& instance()
{
return singletonM;
}
int getValue(){ return i}
void setValue(int x){ i=x ;}
};
Singleton Singleton::s(48);
int main()
{
static Singleton& s = Singleton::instance();
cout<<s.getValue<<endl;
static Singleton& s1. = Singleton::instance();
s1.setValue(9);
cout<<s.getValue()<<endl;
}
创建单例模式关键是:
1.防止客户程序员获得任何控制其对象生存期的权利,因此必须将所有构造函数
声明为私有,并且防止编译器自动生成任何构造函数。
2.决定对象的创建方式。
这里是静态创建,称作惰性初始化。由于实例的创建不受客户程序员控制(在程序开始时初始化),所以
这种实现方式只有在对象创建代价不大,并且并不总是需要它的时候才有意义。
2.Meyers' singleton
class Singleton{ int i; Singleton(int x):i(x){} Singleton& operator=(Singleton&); Singleton(const Singleton&);public: static Singleton& instance()
{
static Singleton s(47);
return s;
}
int getValue(){ return i}
void setValue(int x){ i=x ;}
};这种实现由Meyers最先提出(effective c++),故成为Meyers单例;实例在客户程序员调用 instance()时才会被
初始化。
3.template
4.线程安全
- 单例模式的几种实现及其比较
- 单例模式的几种实现方式比较
- Java 单例模式及其几种实现代码
- 单例模式的几种实现
- 单例模式的几种实现
- 单例模式的几种实现
- 单例模式的几种实现
- 单例模式的几种实现
- 单例模式的几点比较
- 单例模式的几种用法比较
- IOS实现单例模式的几种实现方法
- IOS实现单例模式的几种实现方法
- 单例模式的四种实现及其优缺点
- 单例模式的几种实现方式的对比
- 单例模式及其实现
- java单例模式的几种实现
- JAVA单例模式的几种实现方法
- 单例模式singleton的几种实现方式
- sql 自动编号
- 如何寻找出色的产品经理
- via和pad的区别
- Stack(栈)和Heap(堆)的区别
- Java Thread Join方法
- 单例模式的几种实现及其比较
- 线性表中插入元素
- Linux系统命令及其使用详解
- Ubuntu Linux 8.04系统下智能拼音输入法
- hdu 2883(最大流)
- ASP.NET中MD5和SHA1的几种方法
- Java5泛型的用法,T.class的获取和为擦拭法站台
- 从百度文库看企业内部信息泄漏
- poj1087