单例模式在Java中的7种实现

参考文章链接:
http://www.blogjava.net/kenzhh/archive/2011/09/02/357824.html

1.懒汉模式-非线程安全

/**
 * 懒汉-非线程安全
 * 
 * @author John
 *
 */
public class Singleton1 {
    //声明静态的实例
    private static Singleton1 instance;
    //不允许自己创建实例化
    private Singleton1() {}
    //对外访问实例的静态方法
    public static Singleton1 getInstance() {
        if (instance == null) {
            instance = new Singleton1();
        }
        return instance;
    }
}

2.懒汉模式-线程安全

/**
 * 懒汉-线程安全
 * 
 * @author John
 *
 */
public class Singleton2 {
    //声明静态的实例
    private static Singleton2 instance;
    //不允许自己创建实例化
    private Singleton2() {}
    //对外访问实例的静态方法,关键字synchronized表示该方法是线程同步的
    public static synchronized Singleton2 getInstance() {
        if (instance == null) {
            instance = new Singleton2();
        }
        return instance;
    }
}

3.饿汉模式-声明时初始化-线程安全

/**
 * 饿汉-线程安全
 * 
 * @author John
 *
 */
public class Singleton3 {
    // 声明静态的实例,并在类加载的时候实例化,避免了多线程同步的问题
    private static Singleton3 instance = new Singleton3();
    // 不允许自己创建实例化
    private Singleton3() {}
    // 对外访问实例的静态方法
    public static Singleton3 getInstance() {
        return instance;
    }
}

4.饿汉模式-static块中初始化-线程安全

/**
 * 饿汉-线程安全-在static块初始化
 * 
 * @author John
 *
 */
public class Singleton4 {
    // 声明实例
    private static Singleton4 instance = null;
    // 在static块中对实例进行初始化
    static {
        instance = new Singleton4();
    }
    // 不允许自己创建实例化
    private Singleton4() {}
    // 对外访问实例的静态方法
    public static Singleton4 getInstance() {
        return instance;
    }
}

5.静态内部类-线程安全

/**
 * 静态内部类-线程安全
 * 
 * @author John
 *
 */
public class Singleton5 {
    // 定义静态内部类
    private static class SingletonHolder {
        // 将实例声明为静态常量,并初始化
        private static final Singleton5 INSTANCE = new Singleton5();
    }
    // 不允许自己创建实例化
    private Singleton5() {}
    // 对外访问实例的静态方法,通过静态内部类访问
    public static final Singleton5 getInstance() {
        return SingletonHolder.INSTANCE;
    }
}

6.枚举-线程安全

public enum Singleton6 {
    INSTANCE;
    public void whateverMethod() {
    }
}

7.双重校验锁

public class Singleton7 {
    private volatile static Singleton7 singleton;
    private Singleton7() {}
    public static Singleton7 getSingleton() {
        if (singleton == null) {
            synchronized (Singleton7.class) {
                if (singleton == null) {
                    singleton = new Singleton7();
                }
            }
        }
        return singleton;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值