单例模式分为两种:饿汉模式 懒汉模式
饿汉模式:

//单例模式:饿汉模式
public class TestSingleton {
//1、私有化构造
private TestSingleton(){
}
//2、私有静态属性对象实例
private static final TestSingleton singleton=new TestSingleton();
//3、公开获取实例方法
public static TestSingleton getTestObject() {
return singleton;
}
}
懒汉模式:

//单例模式:懒汉模式
class TestSingleton{
//1、私有化构造
private TestSingleton(){
}
//2、私有静态属性唯一对象引用
private static TestSingleton singleton;
//3、公开获取实例方法(懒汉模式有个缺点在多线程时候可能创建多个对象)
public static TestSingleton getTestObject() {
if(singleton==null) {
singleton=new TestSingleton();
}
return singleton;
}
}
恶汉模式在开启多线程的时候有可能出现创建多个对象的问题,下面进行优化:获取对象方法加同步锁
优化:

//单例模式:懒汉模式
class TestSingleton{
//1、私有化构造
private TestSingleton(){
}
//2、私有静态属性唯一对象引用
private static TestSingleton singleton;
//3、公开获取实例方法(优化:加同步锁)
public static synchronized TestSingleton getTestObject() {
if(singleton==null) {
singleton=new TestSingleton();
}
return singleton;
}
}
来源:https://www.cnblogs.com/2393920029-qq/p/12015193.html
