单例模式

/**
 * Created by wwhhff11 on 16-8-18.
 */
public class Singleton1 {

    private static A a = null;

    private static class A {

    }

    static {
        System.out.println("----static----");
        a = new A();
    }

    // 执行方法时候对象才被创建
    public static A getInstance() {
        System.out.println("------getInstance----");
        return a;
    }

}
/**
 * Created by wwhhff11 on 16-8-18.
 */
public class Singleton1 {

    private static A a = null;

    private static class A {

    }

    // 判断不优雅
    public static A getInstance() {
        System.out.println("------getInstance----");
        if (a == null) {
            synchronized (A.class) {
                a = new A();
            }
        }
        return a;
    }

}
/**
 * Created by wwhhff11 on 16-8-18.
 */
public class Singleton1 {

    private static volatile A a = null;

    private static class A {

    }

    // 判断不优雅
    public static A getInstance() {
        System.out.println("------getInstance----");
        if (a == null) {
            synchronized (A.class) {
                // double check
                // 防止重复创建
                // 如果没有volatile 关键字:不是线程安全的
                // 在new的过程中分为两步:1. 为对象分配空间,并且指向空间 2.初始化对象
                // 如果在其他线程使用到了这个static变量然而不为空,会导致异常
                if (a == null) {
                    a = new A();
                }
            }
        }
        return a;
    }

}

double-check 问题

/**
 * Created by wwhhff11 on 16-8-18.
 */
public class Singleton1 {

    private static A a = null;

    private static class A {

    }

    // 成员内部类优化单例模式
    private static class Factory {
        private static A a = new A();
    }

    public static A getInstance() {
        return Factory.a;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值