单例模式范例

    • 一饿汉式
    • 懒汉式

一、饿汉式

范例:

/**单例模式:之饿汉式 * 特点:类初始化时立即加载。 * 1.加载类时天然线程安全,方法不用同步,调用效率高。 * 2.但是立即加载没有延时加载的优势。 * */
public class Test_Single {
    private static Test_Single instance = new Test_Single(); //2.立即加载对象
    private Test_Single(){   //1.私有化构造器

    }
    public static Test_Single getInstance(){//3.获得实例的方法。
        return instance;
    }

}

2.懒汉式

范例:

/**单例模式:之懒汉式: * 1.特点:很懒,用时才加载,延时加载。资源利用率高。所以当类的调用不频繁,可以用懒汉式。 * 2.必须加线程锁,否则不同的线程会建立不同的对象。 * * */
public class Test_Single {
    private static Test_Single instance ; //2.开始并不加载,用时才加载
    private Test_Single(){   //1.私有化构造器

    }
    public static synchronized Test_Single getInstance(){//3.获得实例的方法。必须加同步
        if(instance==null){
            instance = new Test_Single();
        }
        return instance;
    }

}

你可能感兴趣的:(线程安全,instance)