一、懒汉模式
二、饿汉模式
三、枚举模式
单例模型
保证在内存中有给定数量的对象。
eg.内存中产生唯一一个对象。—国无二主
问题分析
防止外界创建对象
Car c = new Car();
将构造器隐藏起来,防止外界调用。
只初始化、创建一次
static: 类加载的时候初始化一次。
Method区,类加载 Car.class —》类加载器——>内存: 初始化这块空间
懒汉模式
private static Car instance; //instance没有引用对象,
private Car() {
}
public static Car getInstance() { //懒加载
if (Objects.isNull(instance)) {
instance = new Car();
}
return instance;
}
懒汉的困惑
package com.wnhz.singleton.entity;
import java.util.Objects;
public class Car {
private static Car instance; //instance没有引用对象,
private Car() {
}
public static synchronized Car getInstance() { //懒加载
if (Objects.isNull(instance)) {
instance = new Car();
}
return instance;
}
}
- 读数据 a
- 写数据 b
- 读 c
- 写 d
================
1.读数据 a
2. 读 c
3. 写数据 b
4. 写数据 d
public static Car getInstance() { //懒加载
if (Objects.isNull(instance)) {
synchronized (Car.class){
if(Objects.isNull(instance)){
instance = new Car();
}
}
}
return instance;
}
可重入锁
public class Car2 {
private final static ReentrantLock lock = new ReentrantLock();
private static Car2 instance; //instance没有引用对象,
private Car2() {
}
public static Car2 getInstance() { //懒加载
try{
lock.lock();
if(Objects.isNull(instance)){
instance = new Car2();
}
}finally {
lock.unlock();
}
return instance;
}
}
饿汉模式
public class Car3 {
private static Car3 instance = new Car3();
private Car3(){}
public static Car3 getInstance() {
return instance;
}
}
枚举类型
引子
隐藏在mybatisplus中的枚举类。
public enum IdType {
AUTO(0),
NONE(1),
INPUT(2),
ASSIGN_ID(3),
ASSIGN_UUID(4);
private final int key;
private IdType(int key) {
this.key = key;
}
public int getKey() {
return this.key;
}
}
AUTO 表示数字 0 ——>mysql数据库的自增长
产生目的
让我们的项目中的常量可读性增强。
“魔鬼”常量
if(a == Login.ONE_TIME){
}
x = 1;
枚举的语法
public enum Weather {
晴天,雨天 ,雪天,阴天
}
public final class Weather extends java.lang.Enum<Weather> {
public static final Weather SUN;
public static final Weather RAIN;
public static final Weather SNOW;
public static final Weather CLOUD;
public static Weather[] values();
public static Weather valueOf(java.lang.String);
static {};
}
枚举是一个特殊的类
public enum WeatherEnum {
SUNNY(1,"晴天"),
SNOWING(2,"雪天"),
;
private int code;
private String msg;
WeatherEnum(int code, String msg) {
this.code = code;
this.msg = msg;
}
public int getCode(){
return this.code;
}
public String getMsg(){
return this.msg;
}
}
枚举的单例解决方案
public enum Singleton {
INSTANCE;
}