标签:stat 不能 tin on() 命名空间 懒汉式 instance 加载 问题
全局变量和单例模式的区别:
1. 全局变量是对一个对象的静态引用,不能保证只有一个实例;
2. 过多全局变量造成代码难读,命名空间污染;
3. 全局变量不能实现继承;
饿汉模式:在类加载时就实例化类的一个对象
package Singleton;
public class EagerSingleton {
//饿汉单例模式
//在类加载时就完成了初始化,所以类加载较慢,但获取对象的速度快
private static EagerSingleton instance = new EagerSingleton();//静态私有成员,已初始化
private EagerSingleton()
{
//私有构造函数
}
public static EagerSingleton getInstance() //静态,不用同步(类加载时已初始化,不会有多线程的问题)
{
return instance;
}
}
懒汉模式:在需要的时候再创建对象。
package Singleton;
public class LazySingleton1 {
//懒汉式单例模式
//比较懒,在类加载时,不创建实例,因此类加载速度快,但运行时获取对象的速度慢
private static LazySingleton1 instance = null;//静态私用成员,没有初始化
private LazySingleton1()
{
//私有构造函数
}
public static synchronized LazySingleton1 getInstance() //静态,同步,公开访问点
{
if(instance == null)
{
instance = new LazySingleton1();
}
return instance;
}
}
class LazySingleton2 {
private static volatile LazySingleton2 instance = null;//静态私用成员,没有初始化
private LazySingleton2() {}
public static LazySingleton2 getInstance() { //静态,同步,公开访问点
if(instance == null){
synchronized(LazySingleton2.class){
if(instance == null){
instance = new LazySingleton2();
}
}
}
return instance;
}
}
标签:stat 不能 tin on() 命名空间 懒汉式 instance 加载 问题
原文地址:http://www.cnblogs.com/CodeCafe/p/7226651.html