设计模式

设计模式

一、单例模式的几种写法

懒加载-懒汉模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Singleton {

private volatile static Singletoninstance;

private Singleton() {
}

public static Singleton getInstance() {
if (instance==null) { //第一次检查
synchronized (Singleton.class) {
if (instance==null) { //第二次检查
instance=new Singleton();
}
}
}
return instance;
}
}

在上述代码中,使用双重检查锁实现了线程安全的单例模式。getInstance()方法首先检查instance是否为null,如果为null,则进入同步块。在同步块内部,再次检查instance是否为null,这是为了防止多个线程同时通过了第一次检查,然后一个线程创建了实例,而另一个线程又创建了一个实例的情况发生。使用双重检查锁可以在保证线程安全的前提下,减少锁的竞争,提高性能。但需要注意的是,使用双重检查锁需要将instance声明为volatile类型,以确保多线程环境下的可见性。

二、预加载-饿汉模式

1
2
3
4
5
6
7
8
9
10
11
public class Singleton {

private static final Singleton instance = new Singleton();

private Singleton(){
}

public static Singleton getInstance(){
return instance;
}
}

三、静态内部类模式

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Singleton {

private static class SingletonHolder {
private static Singleton instance=new Singleton();
}

private Singleton(){}

public static Singleton getInstance() {
return SingletonHolder.instance;
}
}

枚举模式

1
2
3
4
5
6
7
8
9
10
public enum Singleton {
/**
* 单例实例
*/
INSTANCE;

public void doSomeThing(){
System.out.println("done");
}
}

单元素的枚举类型是实现 Singleton 的最佳方法

二、Spring中的设计模式有哪些

  • 工厂模式: Spring使用工厂模式通过BeanFactory和ApplicationContext创建bean对 象。
  • 单例模式: Spring中的bean默认都是单例的。
  • 代理模式:Spring的AOP功能用到了JDK的动态代理和CGLIB字节码生成技术;

三、MyBatis中有哪些设计模式

  • 工厂模式:例如SqlSessionFactory、ObjectFactory、MapperProxyFactory;
  • 单例模式:例如ErrorContext和LogFactory;
  • 代理模式:Mybatis实现的核心,比如MapperProxy、ConnectionLogger,用的jdk的动态代理;还有executor.loader包使用了cglib或者javassist达到延迟加载的效果;