单例设计模式Singleton之懒加载模式(懒汉模式)【原】

单例设计模式Singleton之懒加载模式(懒汉模式)

SingletonLazy.java类

package kingtool;

import kingtool.http.IPTool;


public class SingletonLazy {
    // 懒汉式单例模式
    // 比较懒,在类加载时,不创建实例,因此类加载速度快,但运行时获取对象的速度慢(第一次)
    private static SingletonLazy intance = null;// 静态私用成员,没有初始化

    
    private String currentIp = "";
    private SingletonLazy() {//所有加载一次的其它类代码都放在这里
        currentIp = IPTool.judgeIP();//其它代码,仅加载一次用
    }

    
    public static synchronized SingletonLazy getInstance() // 静态,同步,公开访问点
    {
        if (intance == null) {
            synchronized (SingletonLazy.class) {
                if (intance == null) {
                    intance = new SingletonLazy();
                }
            }
        }
        return intance;
    }


    public String getCurrentIp() {
        return currentIp;
    }

    public static void main(String[] args) {
        SingletonLazy single = new SingletonLazy();
        single = new SingletonLazy();
        single = new SingletonLazy();
        single = new SingletonLazy();
        single.getCurrentIp();
    }
}

 

posted @ 2017-01-19 14:07  苦涩泪滴  阅读(341)  评论(0编辑  收藏  举报