单例模式特点:一个类只有一个实例。核心: 私有的构造方法,保证外部类不能通过new创建对象。
具体实现方法:
1 懒汉式(线程不安全)
public class SingletonTest {
private static SingletonTest singleton;
private SingletonTest() {
}
public static SingletonTest getInstance(){
if(singleton==null){
singleton=new SingletonTest();
}
return singleton;
}
}
2.懒汉式(线程安全) :在方法上加上synchronized关键字
public class SingletonTest {
private static SingletonTest singleton;
private SingletonTest() {
}
public static synchronized SingletonTest getInstance(){
if(singleton==null){
singleton=new SingletonTest();
}
return singleton;
}
}
饿汉式:每次调用都会创建 消耗资源
public class SingletonTest {
private static SingletonTest singleton=new SingletonTest();;
private SingletonTest() {
}
public static synchronized SingletonTest getInstance(){
singleton=new SingletonTest();
return singleton;
}
}
静态内部类:相比饿汉模式,只有在调用getInstance方法才会初始化对象。
public class SingletonTest {
private SingletonTest() {
}
public static SingletonTest getInstance(){
return Singleton.singleton;
}
private final static class Singleton{
private static SingletonTest singleton=new SingletonTest();
}
}
枚举类
public enum SingletonTest {
instance;
public void getInstance(){
}
}
双重校验锁
public class SingletonTest {
private volatile static SingletonTest singleton;
private SingletonTest() {
}
public static SingletonTest getInstance(){
if(singleton==null){
synchronized(SingletonTest.class){
singleton=new SingletonTest();
}
}
return singleton;
}
}
在多线程中可能会有多个线程同时访问,会创建对个实例,所以需要加锁保证单例。