1、什么是单例ide
一、私有的静态全局变量,变量类型就是该类的类型。测试
二、构造方法私有化(避免使用new去建立对象)spa
三、对外提供公有的静态方法,用于获取该类对象。code
2、单例解决什么问题对象
确保类对象的惟一性(即该类只能有一个对象)blog
3、单例的种类和代码实现get
饿汉模式event
1 public class Singleton { 2 3 private static Singleton instance = null; //静态全局变量
//private static Singleton instance = new Singleton();
4 5 /** 6 私有的构造方法 7 @param 无 8 */ 9 private Singleton(){ 10 11 } 12 13 //静态初始化块 14 static{ 15 instance = new Singleton(); 16 } 17 18 /** 19 静态方法getInstance() 20 @param 无 21 */ 22 public static Singleton getInstance(){ 23 //懒汉模式 24 /*if(instance == null){ 25 instance= new Singleton(); 26 }*/ 27 return instance; 28 } 29 }
测试单例模式class
1 public class SingletonTest { 2 3 /** 4 * @param args 5 */ 6 public static void main(String[] args) { 7 8 //不能经过new来建立对象,由于构造方法私有 9 //Student s3= new Student(); 10 //调用Student类的静态方法获取对象的地址 11 Singleton s1= Singleton.getInstance(); 12 Singleton s2= Singleton.getInstance(); 13 /* 14 比较两个变量的值是否相等若是相等,则代表只建立了一个对象, 15 两个变量都共有该对象的地址 16 */ 17 System.out.println(s1 == s2); 18 } 19 20 }
升级版变量
1 public class Singleton1 { 2 3 private static final class SingletonHolder{ 4 private static final Singleton1 INSTANCE = new Singleton1(); 5 } 6 7 private Singleton1(){ 8 9 } 10 11 public static Singleton1 getInstance(){ 12 return SingletonHolder.INSTANCE; 13 } 14 }
反序列化版
1 public class Singleton2 implements Serializable{ 2 3 //防止建立多个对象 4 private static final class SingletonHolder{ 5 private static final Singleton2 INSTANCE = new Singleton2(); 6 } 7 8 private Singleton2(){ 9 10 } 11 12 public static Singleton2 getInstance(){ 13 return SingletonHolder.INSTANCE; 14 } 15 16 //反序列化 17 private Object readResolve(){ 18 return SingletonHolder.INSTANCE; 19 } 20 } 21 22 //枚举实现单例 23 /* 24 public enumSingleton{ 25 INSTANCE; 26 public File openFile(String fileName){ 27 return getFile(fileName); 28 } 29 }*/
懒汉模式
1 public class Singleton3 { 2 3 private static volatile Singleton3 singleton3; 4 5 private Singleton3(){ 6 7 } 8 9 public static Singleton3 getInstance(){ 10 if(null == singleton3){ 11 synchronized (Singleton3.class) { 12 if(null == singleton3){ 13 singleton3 = new Singleton3(); 14 } 15 } 16 } 17 return singleton3; 18 } 19 20 }