单例模式
2016-10-28 15:18
培训马上就结束了,准备把这些天学到的知识点都归纳总结一下。 单例模式,应该是23种设计模式中最简单的,写法有很多:饿汉式、懒汉式什么的。
2023-07-12
对于应届生,如果简历上写了设计模式,这个大概率是会被提问,
饿汉式
这种写法,本质是 final 变量的应用,final 修饰的对象无法被改变
/**
* 饿汉式
*
* @author Mr.css
* @version 2023-07-12 16:05
*/
public class Test2 {
public static final String singleton = "A";
}
枚举类也属于单例
/**
* 饿汉式
*
* @author Mr.css
* @version 2023-07-12 16:05
*/
public enum Test2 {
ZERO(0), ONE(1);
private int value;
Test2(int value) {
this.value = value;
}
public void setValue(int value) {
this.value = value;
}
}
懒汉式
面试一般要求默写这个代码,
-
掌握 synchronized 关键字的用法
可能会问锁 class 和锁对象实例的区别; 锁 class,new 出来的所有对象都会阻塞,锁对象只会阻塞那个特定的对象。
-
为什么要两次进行 if null 判断?
init() 函数本身不加锁,多个线程可以进入这个函数,
假设有好多个线程都进到这个函数, 到达 synchronized 代码块时,因为加锁,只会有 1 个线程继续执行, 其它线程进入等待,等这个线程执行完毕,其它线程仍然会进入 synchronized 代码块。
/**
* 懒汉式
*
* @author Mr.css
* @version 2023-07-12 16:05
*/
public class Test2 {
public static String singleton;
public void init() {
if (singleton == null) {
synchronized (Test2.class) {
if (singleton == null) {
singleton = "A";
}
}
}
}
}
疯狂的妞妞 :每一天,做什么都好,不要什么都不做!