public class singleton { /** * 预先实例化好了,也可以使用懒实例化,在构造函数中实例化,不过要注意线程同步的位码头 */ private static singleton singleton = new singleton(); /** * 私有构造函数 */ private singleton() { } /** * 对外接口 * @return */ public static singleton getinstance() { return singleton; }} 例子2 懒实例化的单例模式
/** * 使用懒加载方式 */public class singleton2 { private static singleton2 singleton2 = null; private singleton2() { } /** * 缺点是每次都要判断是否为null,而且同步浪费效率 */ public synchronized static singleton2 getinstance() { if (singleton2 == null) { singleton2 = new singleton2(); } return singleton2; }} 例子3 双重成例检查的单例模式
/** * 使用双重成例检查的单例模式 */public class singleton3 { private static singleton3 singleton3 = null; private singleton3() { } /** * 只会判断一次null,效率高了,但是代码稍微复杂了一点 */ public static singleton3 getinstance() { if (singleton3 == null) { synchronized (singleton3.class) { if (singleton3 == null) { singleton3 = new singleton3(); } } } return singleton3; } }
本文深入探讨单例模式的实现策略,包括预先实例化、懒加载和双重检查等方法,并分析各自优缺点及性能考量。通过对比实例,揭示如何在不同场景下选择合适的单例模式实现,以提升程序效率与可维护性。
1871

被折叠的 条评论
为什么被折叠?



