http://794950040.iteye.com/blog/2208102
以上面的饿汉模式实现为基础
/*
* 懒汉模式
*/
public class Singleton2 {
//1.将构造方式私有化,不允许外边直接创建对象
private Singleton2(){
}
}
然后三步走:
1.将构造方法改为私有的
2 .申明类的唯一实例,用private static修饰,但是不实例化
3.在get方法中实例化唯一对象
得到的类为:
/*
* 懒汉模式
*/
public class Singleton2 {
//1.将构造方式私有化,不允许外边直接创建对象
private Singleton2(){
}
//2.声明类的唯一实例,使用private static修饰
private static Singleton2 instance;
//3.提供一个用于获取实例的方法,使用public static修饰
public static Singleton2 getInstance(){
if(instance==null){
instance=new Singleton2();
}
return instance;
}
}
在Test.java类中验证:
public class Test {
public static void main(String[] args) {
//饿汉模式
Singleton s1=Singleton.getInstance();
Singleton s2=Singleton.getInstance();
if(s1==s2){
System.out.println("s1和s2是同一个实例");
}else{
System.out.println("s1和s2不是同一个实例");
}
//懒汉模式
Singleton2 s3=Singleton2.getInstance();
Singleton2 s4=Singleton2.getInstance();
if(s3==s4){
System.out.println("s3和s4是同一个实例");
}else{
System.out.println("S3和s4不是同一个实例");
}
}
}
得到结果:
s1和s2是同一个实例
s3和s4是同一个实例
饿汉模式与懒汉模式的区别:
饿汉模式的特点是加载类时比较慢,但运行时获取对象的速度比较快,线程安全
懒汉模式的对象实例化在类加载的时候,所以加载速度比较慢,但是获取对象的时候就快了。
参考资料:http://www.imooc.com/learn/112