创建模式之Singleton(单态)
来源:互联网 发布:域名 服务器 编辑:程序博客网 时间:2024/05/20 07:20
Singleton模式主要作用是保证在Java应用程序中,一个类Class只有一个实例存在。
一般Singleton模式通常有几种形式:
public class Singleton {
private Singleton(){}
//在自己内部定义自己一个实例,是不是很奇怪?
//注意这是private 只供内部调用
private static Singleton instance = new Singleton();
//这里提供了一个供外部访问本class的静态方法,可以直接访问
public static Singleton getInstance() {
return instance;
}
//当程序第一次调用getInstance的时候初始化Singleton 类 同时初始化static字段 产生唯一的对象实例
}
第二种形式:
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实例。
一般认为第一种形式要更加安全些。
资源引用
http://www.blogjava.net/Swing/articles/120814.html
- 创建模式之Singleton(单态)
- 创建模式之Singleton(单态)
- 创建模式之Singleton(单态)
- 创建型模式-Singleton ( 单态模式 )
- [设计模式-创建型]单态(Singleton)
- 设计模式之Singleton(单态模式)
- 设计模式之Singleton(单态模式)
- 设计模式之Singleton(单态模式)
- 设计模式-创建型模式之 Singleton(单例)
- 创建型模式之单例模式(Singleton)
- 设计模式(创建型)之单例模式(Singleton Pattern)
- 【设计模式】创建型模式之单例Singleton
- 创建型模式之单例模式SINGLETON
- 5种创建型模式之:单例模式 Singleton
- 设计模式之Singleton(单态)
- 设计模式之Singleton(单态)
- 设计模式之Singleton(单态)
- 设计模式之Singleton(单态)
- Java自动设置环境变量
- 结构模式之Bridge
- 结构模式之Decorator(油漆工)
- 结构模式之Composite(组合)
- 结构模式之Proxy(代理)
- 创建模式之Singleton(单态)
- 创建模式之Builder (建设)
- 创建模式之Prototype(原型)
- 创建对象之Factory (工厂)
- struts的html:radio之一默认为选中状态
- html:radio 之二--选中问题
- JS获取radio和checkbox一系列html元素
- html:radio之三默认选中
- 第一篇文章