某个类任何情况下只有一个实例,并提供一个全局访问点来获取该实例。
Java6种单例模式:2种懒汉式,2种饿汉式 ,静态内部类 ,枚举类
public class Singleton {
private static Singleton instance;
private Singleton(){}
public static synchronized Singleton getInstance(){ //synchronized锁住getInstance方法
if (instance==null) { //延迟加载
instance = new Singleton();
}
return instance;
}
}
public class Singleton {
private volatile static Singleton instance; //volatile修饰实例
private Singleton(){}
public static Singleton getInstance(){
if (instance==null) {
synchronized(Singleton.class){ //synchronized锁住Singleton对象
if (instance==null) {
instance = new Singleton();
}
}
}
return instance;
}
}
public class Singleton {
private static Singleton instance = new Singleton(); //类加载时初始化静态实例
private Singleton() {
}
public static Singleton getInstance() {
return instance; //直接返回加载好的静态实例
}
}
public class Singleton {
private static Singleton instance = null;
static{
instance = new Singleton(); //在静态代码块里初始化实例
}
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
}
调用静态内部类时,在静态内部类里初始化实例
public class Singleton {
//定义静态内部类
private static class InnerSingleton {
private static final Singleton INSTANCE = new Singleton(); //初始化完成Singleton类静态实例
}
private Singleton() {
}
public static Singleton getInstance() {
return InnerSingleton.INSTANCE; //返回静态内部类里的静态实例
}
}
创建一个枚举,枚举成员为INSTANCE。使用枚举类.INSTANCE即可获取实例
package acc;
public enum Singleton {
INSTANCE; //定义1个唯一的成员INSTANCE
//枚举类里的公共方法
public void doSomething() {
System.out.println("r2323t23");
}
}
public class TestSingleton {
public static void main(String[] args) {
//使用枚举类.INSTANCE即可获取实例
Singleton.INSTANCE.doSomething();
}
}