单例模式之懒汉式单例模式
1.0 单例模式的定义:
定义:一个类有且仅有一个实例,并且自行实例化向整个系统提供。
1.1代码场景:
A、package内有AppConfig.properties文件。
B、通过获取单例的AppConfigWithLazySingleton对象来读取AppConfig.properties的parameterA和parameterB的值。
1.2代码获取:点击下载(下载后,直接解压,将文件放入Eclipse/IntelliJ IDEA的src下,建议使用电脑浏览器下载)
1.3代码讲解
1.3.1 AppConfig.properties
AppConfig.properties包含两个参数parameterA,parameterB,代码如下:
parameterA=A
parameterB=B
1.3.2 AppConfigWithLazySingleton.java文件
该文件用于创建和获取单例的AppConfigWithLazySingleton对象,主要流程如下:
a、
创建一个static的AppConfigWithEagerSingleton对象,并赋值为null。
b、
私有化构造器
,以确保外界无法随意创建AppConfigWithLazySingleton对象。
c、
提供一个static方法getInstance()
:该方法流程如下,第一判断a步骤的AppConfigWithEagerSingleton对象是否为null,如果为null则创建一个对象,再返回该对象。如果该对象不为null直接返回a步骤的对象。该getInstance()方法需要使用synchronized关键字标识,以保证线程安全。
AppConfigWithLazySingleton.java代码如下:
package singlethon_lazy;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* 读取应用配置文件(使用懒汉式单例模式)
* @author YJ
*/
public class AppConfigWithLazySingleton {
/**要点一:此处不实例化对象*/
private static AppConfigWithLazySingleton appConfigWithLazySingleton=null;
/**参数A*/
private String parameterA;
/**参数B*/
private String parameterB;
/**要点二:私有化构造器*/
private AppConfigWithLazySingleton() {
readConfig();
}
/**要点三 1:提供一个static方法获取单例对象,并且方法上需要使用synchronized进行同步
* 2.先判断对象是否为空,如果为空则先实例化再返回单例对象;否则直接返回单例对象
*/
public static synchronized AppConfigWithLazySingleton getInstance(){
if(appConfigWithLazySingleton==null){
appConfigWithLazySingleton=new AppConfigWithLazySingleton();
}
return appConfigWithLazySingleton;
}
/***
* 读取配置文件
*/
private void readConfig(){
Properties properties=new Properties();
//加载当前package下的的AppConfig.properties
InputStream is=AppConfigWithLazySingleton.class.getResourceAsStream("AppConfig.properties");
try {
properties.load(is);
parameterA=properties.getProperty("parameterA");
parameterB=properties.getProperty("parameterB");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {//释放资源
if(is!=null){
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public String getParameterA() {
return parameterA;
}
public String getParameterB() {
return parameterB;
}
}
1.3.3 客户端AppConfigWithLazySingletonMain.java文件
流程解读:
a、通过获取AppConfigWithLazySingletonMain类的getInstance()获取AppConfigWithLazySingletonMain对象。
b、通过AppConfigWithLazySingletonMain对象获取parameterA、parameterA两个参数的值。
c、打印parameterA、parameterB的值。
代码如下:
package singlethon_lazy;
/***
* 读取应用配置文件(使用懒汉式单例模式)客户端
* @author YJ
*/
public class AppConfigWithLazySingletonMain {
public static void main(String[] args) {
//通过静态方法getInstance()获取单例对象
AppConfigWithLazySingleton appConfigWithLazySingleton=AppConfigWithLazySingleton.getInstance();
//获取参数A和参数B
String parameterA=appConfigWithLazySingleton.getParameterA();
String parameterB=appConfigWithLazySingleton.getParameterB();
//打印参数A和参数B
System.out.println(parameterA);
System.out.println(parameterB);
}
}
1.4 单例模式的思考
1.单例模式的本质:控制实例数目。
2.懒汉式单例模式的流程图如下: