单例模式
package singleModel;
import sun.security.jca.GetInstance;
public class SingleOne {
//懒汉模式 非线程安全
/*private SingleOne(){};//私有化构造方法,不允许在外部初始化
private static SingleOne singleOne = null;
public static SingleOne getInstance(){
if (singleOne == null) {
singleOne = new SingleOne();
}
return singleOne;
}*/
//懒汉模式 加同步锁 双重检查锁定
/* private SingleOne(){};
private static SingleOne singleOne = null;
public SingleOne getInstance(){
if (singleOne == null) {
synchronized (SingleOne.class) {
if (singleOne == null) {
singleOne = new SingleOne();
}
}
}
return singleOne;
}*/
//静态内部类
private static class LazyHolder{
private static final SingleOne instance = new SingleOne();
}
private SingleOne(){};
public static final SingleOne getInstance(){
return LazyHolder.instance;
}
//饿汉模式
/*private SingleOne(){};
private static final SingleOne singleOne = new SingleOne();//类再创建的时候会初始化一个对象
public SingleOne getInstance(){
return singleOne;
}*/
//区别:
//懒汉:线程不安全 饿汉:线程安全
//懒:方法调用的时候才会创建对象,第一次调用的时候,相应的速度回慢 饿:类创建的时候初始化一个对象,相应的会占用一定的内存,但是第一次调用时候会快
}
import sun.security.jca.GetInstance;
public class SingleOne {
//懒汉模式 非线程安全
/*private SingleOne(){};//私有化构造方法,不允许在外部初始化
private static SingleOne singleOne = null;
public static SingleOne getInstance(){
if (singleOne == null) {
singleOne = new SingleOne();
}
return singleOne;
}*/
//懒汉模式 加同步锁 双重检查锁定
/* private SingleOne(){};
private static SingleOne singleOne = null;
public SingleOne getInstance(){
if (singleOne == null) {
synchronized (SingleOne.class) {
if (singleOne == null) {
singleOne = new SingleOne();
}
}
}
return singleOne;
}*/
//静态内部类
private static class LazyHolder{
private static final SingleOne instance = new SingleOne();
}
private SingleOne(){};
public static final SingleOne getInstance(){
return LazyHolder.instance;
}
//饿汉模式
/*private SingleOne(){};
private static final SingleOne singleOne = new SingleOne();//类再创建的时候会初始化一个对象
public SingleOne getInstance(){
return singleOne;
}*/
//区别:
//懒汉:线程不安全 饿汉:线程安全
//懒:方法调用的时候才会创建对象,第一次调用的时候,相应的速度回慢 饿:类创建的时候初始化一个对象,相应的会占用一定的内存,但是第一次调用时候会快
}
http://blog.csdn.net/jason0539/article/details/23297037/