工厂方法模式
模式简述

Spring中的FactoryBean
- Product ->
BeanObject
- Concrete Products -> e.g.如mybatis中的
T MapperObject
- Creator ->
FactoryBean
public interface FactoryBean<T> {
T getObject() throws Exception;
Class<?> getObjectType();
boolean isSingleton();
}
- Concrete Creator -> e.g.
MapperFactoryBean
public class MapperFactoryBean<T> extends SqlSessionDaoSupport implements FactoryBean<T> {
public T getObject() throws Exception {
return this.getSqlSession().getMapper(this.mapperInterface);
}
public Class<T> getObjectType() {
return this.mapperInterface;
}
public boolean isSingleton() {
return true;
}
}
策略模式
模式简述

Spring中的InstantiationStrategy
- Context ->
AbstractAutowireCapableBeanFactory
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory {
private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();
public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy) {
this.instantiationStrategy = instantiationStrategy;
}
public InstantiationStrategy getInstantiationStrategy() {
return instantiationStrategy;
}
protected Object createBeanInstance(BeanDefinition bd, String beanName, Object[] args) throws BeansException {
Constructor constructorToUse = null;
Class<?> beanClass = bd.getBeanClass();
Constructor<?>[] declaredConstructors = beanClass.getDeclaredConstructors();
for (Constructor ctor: declaredConstructors) {
if (null != args && ctor.getParameterTypes().length == args.length) {
constructorToUse = ctor;
break;
}
}
return getInstantiationStrategy().instantiate(bd, beanName, constructorToUse, args);
}
}
- Strategy ->
InstantiationStrategy
public interface InstantiationStrategy {
Object instantiate(BeanDefinition bd, String beanName, Constructor ctor, Object[] args) throws BeansException;
}
- Concrete Strategy ->
CglibSubclassingInstantiationStrategy
/SimpleInstantiationStrategy
观察者模式
模式简述

Spring中的ApplicationListener
public interface ApplicationEventPublisher {
void publishEvent(ApplicationEvent event);
}
- 具体发布者 ->
AbstractApplicationContext
public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {
public static final String APPLICATION_EVENT_MULTICASTER_BEAN_NAME = "applicationEventMulticaster";
private ApplicationEventMulticaster applicationEventMulticaster;
@Override
public void publishEvent(ApplicationEvent event) {
applicationEventMulticaster.multicastEvent(event);
}
}
- 广播中介 ->
SimpleApplicationEventMulticaster
public abstract class AbstractApplicationEventMulticaster implements ApplicationEventMulticaster, BeanFactoryAware {
public final Set<ApplicationListener<ApplicationEvent>> applicationListeners = new LinkedHashSet<>();
private BeanFactory beanFactory;
@Override
public void addApplicationListener(ApplicationListener<?> listener) {
applicationListeners.add((ApplicationListener<ApplicationEvent>) listener);
}
@Override
public void removeApplicationListener(ApplicationListener<?> listener) {
applicationListeners.remove(listener);
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
protected Collection<ApplicationListener> getApplicationListeners(ApplicationEvent event) {
LinkedList<ApplicationListener> allListeners = new LinkedList<ApplicationListener>();
for (ApplicationListener<ApplicationEvent> listener: applicationListeners) {
if (supportsEvent(listener, event)) {
allListeners.add(listener);
}
}
return allListeners;
}
}
public class SimpleApplicationEventMulticaster extends AbstractApplicationEventMulticaster {
public SimpleApplicationEventMulticaster(BeanFactory beanFactory) {
setBeanFactory(beanFactory);
}
@SuppressWarnings("unchecked")
@Override
public void multicastEvent(final ApplicationEvent event) {
for (final ApplicationListener listener: getApplicationListeners(event)) {
listener.onApplicationEvent(event);
}
}
}
- 订阅者 -> ApplicationListener
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
void onApplicationEvent(E event);
}
- 具体订阅者 ->
CustomEventListener
, ContextRefreshedEventListener
, ContextClosedEventListener
- 客户端
模板方法模式
模式简述

Spring中的AbstractApplicationContext::refresh()
- 抽象类 ->
AbstractApplicationContext
public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {
public static final String APPLICATION_EVENT_MULTICASTER_BEAN_NAME = "applicationEventMulticaster";
private ApplicationEventMulticaster applicationEventMulticaster;
@Override
public void refresh() throws BeansException {
refreshBeanFactory();
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
invokeBeanFactoryPostProcessors(beanFactory);
registerBeanPostProcessors(beanFactory);
initApplicationEventMulticaster();
registerListeners();
beanFactory.preInstantiateSingletons();
finishRefresh();
}
protected abstract void refreshBeanFactory() throws BeansException;
private void initApplicationEventMulticaster() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, applicationEventMulticaster);
}
private void registerListeners(){
Collection<ApplicationListener> applicationListeners = getBeansOfType(ApplicationListener.class).values();
for (ApplicationListener listener: applicationListeners) {
applicationEventMulticaster.addApplicationListener(listener);
}
}
}
- 具体类 ->
AbstractRefreshableApplicationContext
public abstract class AbstractRefreshableApplicationContext extends AbstractApplicationContext {
private DefaultListableBeanFactory beanFactory;
@Override
protected void refreshBeanFactory() throws BeansException {
DefaultListableBeanFactory beanFactory = createBeanFactory();
loadBeanDefinitions(beanFactory);
this.beanFactory = beanFactory;
}
private DefaultListableBeanFactory createBeanFactory() {
return new DefaultListableBeanFactory();
}
protected abstract void loadBeanDefinitions(DefaultListableBeanFactory beanFactory);
@Override
protected ConfigurableListableBeanFactory getBeanFactory() {
return beanFactory;
}
}
适配器模式
模式简述

Spring中的DisposableBeanAdapter
- 客户端
- 客户端接口 ->
DisposableBean
public interface DisposableBean{
void destroy() throws Exception;
}
- 服务 ->
<destroyMethod>.invoke()
- 适配器 ->
DisposableBeanAdapter
反射调用销毁方法和接口调用销毁方法是两种方式,需要使用适配器统一处理
public class DisposableBeanAdapter implements DisposableBean {
private final Object bean;
private final String beanName;
private String destroyMethodName;
public DisposableBeanAdapter(Object bean, String beanName, BeanDefinition beanDefinition) {
this.bean = bean;
this.beanName = beanName;
this.destroyMethodName = beanDefinition.getDestroyMethodName();
}
@Override
public void destroy() throws Exception {
if (bean instanceof DisposableBean) {
((DisposableBean) bean).destroy();
}
if (StrUtil.isNotEmpty(destroyMethodName) && !(bean instanceof DisposableBean && "destroy".equals(this.destroyMethodName))) {
Method destroyMethod = bean.getClass().getMethod(destroyMethodName);
if (null == destroyMethod) {
throw new BeansException("Couldn't find a destroy method named'" + destroyMethodName + "' on bean " +
"with name '" + beanName + "'");
}
destroyMethod.invoke(bean);
}
}
}
代理模式
模式简述

ProxyBeanFactory
public class ProxyBeanFactory implements FactoryBean<IUserDao> {
@Override
public IUserDao getObject() throws Exception {
InvocationHandler handler = ((proxy, method, args) -> {
Map<String, String> hashMap = new HashMap<>();
hashMap.put("10001", "小梁");
return "你被代理了" + method.getName() + ": " + hashMap.get(args[0].toString());
});
return (IUserDao) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
new Class[]{IUserDao.class}, handler);
}
@Override
public Class<?> getObjectType() {
return IUserDao.class;
}
@Override
public boolean isSingleton() {
return true;
}
}