一、单例模式
代码如下(示例):
/**
* 饿汉式
* 1.类加载到内存后,就实例化一个单例,JVM保证线程安全
* 2.简单实用
* 3.唯一缺点:不管用不用,类加载时就完成实例化
*/
public class Test01 {
private static final Test01 INSTANCE = new Test01();
private Test01() {
}
public static Test01 getInstance() {
return INSTANCE;
}
public static void main(String[] args) {
Test01 test01 = Test01.getInstance();
Test01 test02 = Test01.getInstance();
System.out.println(test01== test02);
}
}
/**
* 饿汉式
* 第二种写法 静态代码块
*/
public class Test02 {
private static final Test02 INSTANCE;
static {
INSTANCE = new Test02();
}
private Test02() {
}
public static Test02 getInstance() {
return INSTANCE;
}
}
/**
* 懒汉式
* 1.达到了使用的时候初始化,但是会有线程安全问题。
*/
public class Test03 {
private static Test03 INSTANCE;
private Test03() {
}
// 可以通过synchronized解决,但是会带来效率下降
public static Test03 getInstance() {
if (INSTANCE == null) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
INSTANCE = new Test03();
}
return INSTANCE;
}
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
new Thread(() ->
System.out.println(Test03.getInstance().hashCode())
).start();
}
}
}
/**
* 静态内部类方式
* JVM保证单例
* 加载外部类时不会加载内部类,这样可以实现懒加载
*/
public class Test05 {
private Test05() {
}
private static class Tets05Holder {
private final static Test05 INSTANCE = new Test05();
}
public static Test05 getInstance(){
return Tets05Holder.INSTANCE;
}
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
new Thread(() ->
System.out.println(Test05.getInstance().hashCode())
).start();
}
}
}
/**
* 不仅可以解决线程同步,还可以防止反序列化
*/
public enum Test06 {
INSTANCE;
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
new Thread(() ->
System.out.println(Test06.INSTANCE.hashCode())
).start();
}
}
}