设计模式,单例这个模式用得应该很频繁
直接介绍几种线程安全的且我觉得还比较不错的方式:
1、是不是号称恶汉,就是类加载就初始化了
[java] view plaincopy在CODE上查看代码片派生到我的代码片
package com.zhy.pattern.singlton;
public class Singleton
{
private static Singleton instance = new Singleton();
public static Singleton getInstance()
{
return instance ;
}
}
2、懒汉,我喜欢这种,需要双重判断
[java] view plaincopy在CODE上查看代码片派生到我的代码片
package com.zhy.pattern.singlton;
public class Singleton02
{
private static Singleton02 instance;
public static Singleton02 getInstance()
{
if (instance == null)
{
synchronized (Singleton02.class)
{
if (instance == null)
{
instance = new Singleton02();
}
}
}
return instance;
}
}
3、使用Java的枚举,还是很推荐的,简单的跟神马一样,如果对枚举不熟悉,小google一下
[java] view plaincopy在CODE上查看代码片派生到我的代码片
public enum Singleton03
{
INSTANCE;
}
4、使用一个持有类,主要是为了不在初始化的时候加载
[java] view plaincopy在CODE上查看代码片派生到我的代码片
package com.zhy.pattern.singlton;
public class Singleton04
{
private static final class InstanceHolder
{
private static Singleton04 INSTANCE = new Singleton04();
}
public static Singleton04 getInstance()
{
return InstanceHolder.INSTANCE;
}
}
|
|