单例设计模式:保证该实例只能创建一个对象
技术实现:1、私有化构造方法
2、创建一个公共的静态方法,用于创建该实例
单例模式分为懒汉式和饿汉式
饿汉式:无论是否需要该实例,首先都会创建一个对象,代码如下:
public class Singleton{
private Singleton(){} // 私有化构造方法
private static Singleton instance = new Singleton();
public static Singleton getInstance(){
return instance;
}
}
饿汉式是线程安全的
懒汉式:只有当需要该实例的时候才创建对象,代码如下:
public class Singleton{
private Singleton(){} // 私有化构造方法
private static Singleton instance;
public static Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
从上述代码可知,懒汉式是线程不安全的,为了实现线程安全,可将方法写为同步方法(在方法中加了synchronized ):
public class Singleton{
private Singleton(){} // 私有化构造方法
private static Singleton instance;
public static synchronized Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}