单例模式
单例模式,即single(单一),也就是说整个程序启动后只有这一个实例化对象.也就是static属性.单例模式的应用场景一般是配置文件,比方说日志.
在单例模式中分为懒汉模式和饿汉模式,饿汉顾名思义,很饥渴,在类加载时初始化:public static Xxx xxx = new Xxx();而懒汉则是需要用到的时候再进行初始化,代码如下:
public class ServerConfig {
public static ServerConfig serverConfig;
/**
* 饿汉模式,在类加载时初始化
* public static ServerConfig serverConfig = new ServerConfig();
*/
/**
* 懒汉模式,在使用时初始化
*/
public static ServerConfig getServerConfig() {
if (serverConfig == null){
try {
//模拟在创建对象前的准备工作,例如读取配置文件之类的操作
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
serverConfig = new ServerConfig();
}
return serverConfig;
}
/**
* 设定构造方法权限为私有,也就是说只能够通过getServerConfig()方法获得ServerConfig对象
* @see #getServerConfig()
*/
private ServerConfig(){
}
}
多线程环境下的懒汉模式设计
public class ServerConfig{
private volatile ServerConfig instance = null;
// 构造方法一定要私有, 因为单例模式本身就是只new一次
// 如果使用其他权限代表别的类也可以创建这个单例对象,不满足单例的定义
private ServerConfig(){
}
public static ServerConfig getInstance(){
// 第一重检查,为了避免使用锁带来的性能消耗
if (instance == null){
// 使用类锁确保只有一个线程能够进入实例创建的代码块
// 注意,可能会有多个线程阻塞在这个位置
synchronized (ServerConfig.class){
// 因为可能有多个线程阻塞在上面的位置
// 第二重检查
if(instance == null){
instance = new ServerConfig();
}
}
}
return instance;
}
}