单例模式的Seven种写法
来源:互联网 发布:science online数据库 编辑:程序博客网 时间:2024/06/16 06:05
//1.懒汉模式 线程不安全
public class Singleton
{
static Singleton singleton;
private Singleton()
{}
public static Singleton GetInstance()
{
if( singleton==null )
{
singleton = new Singleton(); //实例化对象
}
return singleton;
}
}
///////////////////////////////////////////////////////////////////////////
//懒汉模式 线程安全(加锁操作)
static Singleton singleton;
public static synchronized Singleton GetInstance()
{
if( singleton==null )
{
singleton = new Singleton();
}
return singleton;
}
///////////////////////////////////////////////////////////////////////////
//3. 饿汉模式 非变种
static Singleton sigleton = new Singleton(); //饿汉就是直接构造
//构造方法私有化
public static Singleton GetInstance()
{
return singleton;
}
/////////////////////////////////////////////////////////////////////////
//4.饿汉模式 变种 —->最饿的模式,在静态快里new对象
static Singleton singleton = null;
//构造方法私有
static{
singleton = new Singleton(); //程序开始先执行静态块,就是先构造对象
}
public static Singleton GetInstance()
{
return singleton;
}
///////////////////////////////////////////////////////////////////////
//5.静态内部类
private static class SingHand{
//内部类构造方法私有化
private static final Singleton singleton = new Singleton; //!!!!!!!!!!!!!
}
public static Singleton GetInstance
{
return SingHand.singleton;
}
///////////////////////////////////////////////////////////
//枚举法
///////////////////////////////////////////////////////////////////////
//双重校验锁 –>2的升级版
static Singleton singleton=null;
public static Singleton GetInstance()
{
if( singleton == null )
{
synchronized( Singleton.class );
if( singleton == null )
{
singleton = new Singleton();
}
}
}
- 单例模式的Seven种写法
- 单例模式的7种写法
- 单例模式的七种写法
- 单例模式的4种写法
- 单例模式的七种写法
- 单例模式的七种写法
- 单例模式的7种写法
- 单例模式的七种写法
- 单例模式的5种写法
- 单例模式的5种写法
- 单例模式的七种写法
- 单例模式的5种写法
- 单例模式的七种写法
- 单例模式的七种写法
- 单例模式的七种写法
- 单例模式的七种写法
- 单例模式的七种写法
- 单例模式的七种写法
- java内存模型
- 数据结构 P49 栈的应用举例-括号匹配的检验
- 斜率优化DP
- Xml和dom4j
- 龙哥带你玩转面试(1.0)
- 单例模式的Seven种写法
- Java学习笔记-循环
- MySQL遇到的问题-1-ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld
- codevs 1046 旅行家的预算(贪心)
- 【猿小白】常见Python面试问题汇总~~~持续更新~~~直到拿到心仪的offer
- QScintilla2 Unknown module(s) in QT: designer
- 数字通信基础(华为公开课)——笔记
- Jquery如何使用csrf
- 手机移动端web资源整合