对于单例,网上有很多例子,这里就是为了记录一下。
1、懒汉式
①懒汉式-简单
//简单懒汉式
public class Singleton {
//单例实例变量
private static Singleton instance = null;
//私有化的构造方法,保证外部的类不能通过构造器来实例化
private Singleton() {}
//获取单例对象实例
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
System.out.println("简单懒汉式单例!");
return instance;
}
}
②懒汉式-线程安全
public class Singleton {
//单例实例变量
private static Singleton instance = null;
//只实例化一次
static{
instance = new Singleton();
}
//私有化的构造方法,保证外部的类不能通过构造器来实例化
private Singleton() {}
//获取单例对象实例
public synchronized static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
System.out.println("线程安全懒汉式单例!");
return instance;
}
}
2、饿汉式
//饿汉式
public class Singleton {
//单例实例变量,static的,在类加载时进行初始化一次,保证线程安全
private static Singleton instance = new Singleton();
//私有化的构造方法,保证外部的类不能通过构造器来实例化。
private Singleton() {}
//获取单例对象实例
public static Singleton getInstance() {
System.out.println("饿汉式单例!");
return instance;
}
}