标签:style blog color java div sp log c new
1.饿汉式
1 package singleInstance; 2 /**饿汉式,类加载时候创建实例,浪费资源,线程是安全的*/ 3 public class SingleDome01 { 4 //私有构造方法,防止直接new对象 5 private SingleDome01() { 6 } 7 //类加载的时候,创建对象 8 private static SingleDome01 instance = new SingleDome01(); 9 //提供getter,方便外界访问私有对象 10 11 public static SingleDome01 getInstance() { 12 return instance; 13 } 14 }
2.懒汉式
1 package singleInstance; 2 /**懒汉式,被调用时候才会实例化,节约资源,高并发线程时不安全*/ 3 public class SingleDome02 { 4 //私有构造方法,防止直接new对象 5 private SingleDome02(){ 6 } 7 private static SingleDome02 instance; 8 //提供getter,以便外界调用私有对象,返回SingleDome02对象 9 public static SingleDome02 getInstance() { 10 if(instance==null){ 11 instance = new SingleDome02(); 12 } 13 return instance; 14 } 15 }
标签:style blog color java div sp log c new
原文地址:http://www.cnblogs.com/miyin/p/3963316.html