单例模式的最佳实现

public class Singleton {
    // Private constructor prevents instantiation from other classes
    private Singleton() { }

    /**
    * SingletonHolder is loaded on the first execution of Singleton.getInstance() 
    * or the first access to SingletonHolder.INSTANCE, not before.
    */
    private static class SingletonHolder { 
            public static final Singleton INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
            return SingletonHolder.INSTANCE;
    }
}

99%的Java程序员实现不了一个完美的单例模式,看看Wiki上给出的最佳实现:http://t.cn/zOvZMy3 通过单例模式全面了解Double-checked locking以及并发时候的锁的问题:http://t.cn/aKbmIb 

Eager initialization

If the program will always need an instance, or if the cost of creating the instance is not too large in terms of time/resources, the programmer can switch to eager initialization, which always creates an instance:

public class Singleton {
    private static final Singleton instance = new Singleton(); 
    public static Singleton getInstance() {
        return instance;
    }
}
This method has a number of advantages:
The instance is not constructed until the class is used.
There is no need to synchronize the getInstance() method, meaning all threads will see the same instance and no (expensive) locking is required.
The final keyword means that the instance cannot be redefined, ensuring that one (and only one) instance ever exists.


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值