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 public static SingleDome01 getInstance() { 11 return instance; 12 } 13 }
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 }
3.饿汉式与懒汉式改良
1 package singleInstance; 2 /**采用内部类实例化对象,在调用时候才会加载,节约资源,还能保证线程是安全的*/ 3 public class SingleDome03 { 4 //私有构造方法,防止直接new对象 5 private SingleDome03() { 6 } 7 //静态内部类只有在调用时候才会加载 8 private static class InnerSingleDome03{ 9 private static SingleDome03 instance = new SingleDome03(); 10 } 11 public static SingleDome03 getInstance(){ 12 return InnerSingleDome03.instance; 13 } 14 }
4.登记式
1 package singleInstance; 2 3 import java.util.HashMap; 4 import java.util.Map; 5 6 /**采用spring的用法,利用反射创建对象,讲实例注册到map里面,下次用的时候直接取*/ 7 public class SingleDome04 { 8 //私有构造方法,防止外部直接new对象 9 private SingleDome04() { 10 } 11 private static Map<String,SingleDome04> map = new HashMap<String,SingleDome04>(); 12 //静态代码块,类加载时候实例化对象和map,并将对象放入map里 13 static{ 14 SingleDome04 instance = new SingleDome04(); 15 map.put(instance.getClass().getName(), instance); 16 } 17 public static SingleDome04 getInstance(String name){ 18 if(name==null){ 19 name="singleInstance.SingleDome04"; 20 } 21 if(!map.containsKey(name)){ 22 try { 23 map.put(name, (SingleDome04)Class.forName(name).newInstance()); 24 } catch (InstantiationException e) { 25 e.printStackTrace(); 26 } catch (IllegalAccessException e) { 27 e.printStackTrace(); 28 } catch (ClassNotFoundException e) { 29 e.printStackTrace(); 30 } 31 } 32 return map.get(name); 33 } 34 }
最后测试代码:
1 package singleInstance; 2 3 public class TestSingle { 4 public static void main(String[] args) { 5 SingleDome01 s1 = SingleDome01.getInstance(); 6 SingleDome01 s2 = SingleDome01.getInstance(); 7 if(s1==s2){ 8 System.out.println("s1=s2"); 9 }else{ 10 System.out.println("s1!=s2"); 11 } 12 SingleDome02 s3 = SingleDome02.getInstance(); 13 SingleDome02 s4 = SingleDome02.getInstance(); 14 if(s3==s4){ 15 System.out.println("s3=s4"); 16 }else{ 17 System.out.println("s3!=s4"); 18 } 19 SingleDome03 s5 = SingleDome03.getInstance(); 20 SingleDome03 s6 = SingleDome03.getInstance(); 21 if(s5==s6){ 22 System.out.println("s5=s6"); 23 }else{ 24 System.out.println("s5!=s6"); 25 } 26 SingleDome04 s7 = SingleDome04.getInstance("singleInstance.SingleDome04"); 27 SingleDome04 s8 = SingleDome04.getInstance("singleInstance.SingleDome04"); 28 if(s7==s8){ 29 System.out.println("s7=s8"); 30 }else{ 31 System.out.println("s7!=s8"); 32 } 33 } 34 }