方法一
//懒加载(多线程安全) 双重检验
@Data
public class Singleton01 {
private String name;
private int age;
//step1 声明一个volatile static 的Singleton01
private volatile static Singleton01 singleton01;
//step2 私有的构造函数
private Singleton01(){
}
//step3 一个对外获取实例的方法
public static Singleton01 getInstance(){
if(singleton01==null){
synchronized (Object.class){
if(singleton01==null){
singleton01=new Singleton01();
}
}
}
return singleton01;
}
}
方法二
//懒加载(多线程安全) 静态内部类的方法实现
@Data
public class Singleton02 {
private String name;
private int age;
//step1
private Singleton02(){
}
//step2 静态内部类
private static class inner{
private static final Singleton02 singleton02 = new Singleton02();//final 保证指针地址不变
}
public static Singleton02 getInstance(){
return inner.singleton02;
}
}
方法三
饿汉模式 通过枚举来创建单例(默认多线程安全) 枚举单例相对于静态枚举单例同样是没有达到懒加载。
public enum Singleton03 {
people;
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
方法四
//饿汉模式(多线程安全)
@Data
public class Singleton04 {
private String name;
private int age;
//step1
private static Singleton04 singleton04 = new Singleton04();
//step2
private Singleton04(){}//限制方法权限
//step3
public static Singleton04 getInstance(){
return singleton04;
}
}
调用
public class Main {
@Test
public void method01() {
Singleton01 sgt1 = Singleton01.getInstance();
Singleton01 sgt2 = Singleton01.getInstance();
System.out.println("sgt1==sgt2 " + (sgt1 == sgt2));
sgt1.setName("小军");
System.out.println(sgt2.getName());
}
@Test
public void method02() {
Singleton02 sgt1 = Singleton02.getInstance();
Singleton02 sgt2 = Singleton02.getInstance();
System.out.println("sgt1==sgt2 " + (sgt1 == sgt2));
sgt1.setName("小军");
System.out.println(sgt2.getName());
}
@Test
public void method03() {
Singleton03 sgt1 = Singleton03.people;
sgt1.setName("小军");
Singleton03 sgt2 = Singleton03.people;
System.out.println(sgt2.getName());
}
@Test
public void method04() {
Singleton04 sgt1 = Singleton04.getInstance();
Singleton04 sgt2 = Singleton04.getInstance();
System.out.println("sgt1==sgt2 " + (sgt1 == sgt2));
sgt1.setName("小军");
System.out.println(sgt2.getName());
}
}
参考文档
单利模式
https://www.jianshu.com/p/3bfd916f2bb2
https://www.jianshu.com/p/4ea271ee7429