设计模式学习----Singleton单态模式
来源:互联网 发布:淘宝折扣商城在哪里 编辑:程序博客网 时间:2024/05/17 07:38
单态定义:
Singleton模式主要作用是保证在应用程序中,一个类Class只有一个实例存在。
如何使用?
一般Singleton模式通常有几种形式:
第一种形式:
public class Singleton {
private Singleton(){}
//在自己内部定义自己一个实例,是不是很奇怪?
//注意这是private 只供内部调用
private static Singleton instance = new Singleton();
//这里提供了一个供外部访问本class的静态方法,可以直接访问
public static Singleton getInstance() {
return instance;
}
}
第二种形式:
public class Singleton {
private static Singleton instance = null;
public static synchronized Singleton getInstance() {
if (instance==null)
instance=new Singleton();
return instance; }
}
使用Singleton.getInstance()可以访问单态类。
上面第二中形式是lazy initialization,也就是说第一次调用时初始Singleton,以后就不用再生成了。
注意到lazy initialization形式中的synchronized,这个synchronized很重要,如果没有synchronized,
那么使用getInstance()是有可能得到多个Singleton实例。
一般认为第一种形式要更加安全些。
使用Singleton注意事项:
有时在某些情况下,使用Singleton并不能达到Singleton的目的,如有多个Singleton对象同时被不同的类
装入器装载;在EJB这样的分布式系统中使用也要注意这种情况,因为EJB是跨服务器,跨JVM的。
- 设计模式学习----Singleton单态模式
- Singleton(单态设计模式)
- 设计模式--单态(Singleton)
- Java设计模式:Singleton(单态模式)
- 设计模式笔记:单态模式(Singleton)
- 设计模式之Singleton(单态模式)
- 设计模式之Singleton(单态模式)
- 设计模式之Singleton(单态模式)
- 设计模式 -- Singleton单态模式
- 设计模式之Singleton模式(单身模式,单态模式)
- 设计模式之Singleton(单态)
- 设计模式之Singleton(单态)
- 设计模式之Singleton(单态)
- 设计模式之Singleton(单态)
- 设计模式之Singleton(单态)
- 设计模式之Singleton(单态)
- 设计模式之Singleton(单态)
- 设计模式之Singleton(单态)
- 多线程:C#线程同步lock,Monitor,Mutex,同步事件和等待句柄(中)
- C语言中全局变量的定义与调用
- 多线程:C#线程同步lock,Monitor,Mutex,同步事件和等待句柄(下)
- rpm检测是否被篡改
- 狼性管理
- 设计模式学习----Singleton单态模式
- HGE系列之零 使用细究
- How to avoid the "enumeral mismatch" error in eikmenup.h
- samba libtalloc.so.1 : cannot open shared object file: no such file or directory
- mysql修改密码(包括密码忘记的情况)
- Linux操作系统6个应急处理小常识
- select的事件
- 如何做生意:你有没有这方面的头脑?
- matlab中 交互式画线