单例模式,单例模式
单例模式
单例模式通常有两种表现形式:懒汉式单例和饿汉式单例。
1.懒汉式单例:该模式特点是类在加载的过程的时候没有生成一个单例、只有当调用的时候才去创建这个单例。
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
1 public class LazySingleton 2 { 3 private static volatile LazySingleton instance=null; //保证 instance 在所有线程中同步 4 private LazySingleton(){} //private 避免类在外部被实例化 5 public static synchronized LazySingleton getInstance() 6 { 7 //getInstance 方法前加同步 8 if(instance==null) 9 { 10 instance=new LazySingleton(); 11 } 12 return instance; 13 } 14 }

2.饿汉式单例:该模式的特点是类一旦加载就创建一个单例,保证在调用 getInstance 方法之前单例已经存在了。

1 public class HungrySingleton 2 { 3 private static final HungrySingleton instance=new HungrySingleton(); 4 private HungrySingleton(){} 5 public static HungrySingleton getInstance() 6 { 7 return instance; 8 } 9 }

单例模式通常有两种表现形式:懒汉式单例和饿汉式单例。
1.懒汉式单例:该模式特点是类在加载的过程的时候没有生成一个单例、只有当调用的时候才去创建这个单例。

1 public class LazySingleton 2 { 3 private static volatile LazySingleton instance=null; //保证 instance 在所有线程中同步 4 private LazySingleton(){} //private 避免类在外部被实例化 5 public static synchronized LazySingleton getInstance() 6 { 7 //getInstance 方法前加同步 8 if(instance==null) 9 { 10 instance=new LazySingleton(); 11 } 12 return instance; 13 } 14 }

2.饿汉式单例:该模式的特点是类一旦加载就创建一个单例,保证在调用 getInstance 方法之前单例已经存在了。

1 public class HungrySingleton 2 { 3 private static final HungrySingleton instance=new HungrySingleton(); 4 private HungrySingleton(){} 5 public static HungrySingleton getInstance() 6 { 7 return instance; 8 } 9 }


更多精彩