工厂模式
只对结果负责,封装创建过程,如BeanFactory
Object getBean(String name) throws BeansException;
单例模式
保证独一无二,如ApplicationContext
原型模式
拔一根猴毛,吹出千万个,如BeanUtils
public static void copyProperties(Object source, Object target) throws BeansException {
copyProperties(source, target, null, (String[]) null);
}
代理模式
招人办事,增强职责,如JdkDynamicAopProxy
final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializable {
@Override
public Object getProxy(@Nullable ClassLoader classLoader) {
if (logger.isDebugEnabled()) {
logger.debug("Creating JDK dynamic proxy: target source is " + this.advised.getTargetSource());
}
Class<?>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
}
@Override
@Nullable
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
MethodInvocation invocation;
Object oldProxy = null;
boolean setProxyContext = false;
TargetSource targetSource = this.advised.targetSource;
还有CglibAopProxy
class CglibAopProxy implements AopProxy, Serializable {
//...
private static class StaticUnadvisedInterceptor implements MethodInterceptor, Serializable {
@Override
@Nullable
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
Object retVal = methodProxy.invoke(this.target, args);
return processReturnType(proxy, this.target, method, retVal);
}
//...
private static class EqualsInterceptor implements MethodInterceptor, Serializable {
@Override
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) {
Object other = args[0];
if (proxy == other) {
return true;
}
if (other instanceof Factory) {
Callback callback = ((Factory) other).getCallback(INVOKE_EQUALS);
if (!(callback instanceof EqualsInterceptor)) {
return false;
}
AdvisedSupport otherAdvised = ((EqualsInterceptor) callback).advised;
return AopProxyUtils.equalsInProxy(this.advised, otherAdvised);
}
else {
return false;
}
}
//...
委派模式
干活算你的(普通员工),功劳算我的(项目经理),如DispatcherServlet
@Nullable
protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
if (this.handlerMappings != null) {
for (HandlerMapping hm : this.handlerMappings) {
if (logger.isTraceEnabled()) {
logger.trace(
"Testing handler map [" + hm + "] in DispatcherServlet with name '" + getServletName() + "'");
}
HandlerExecutionChain handler = hm.getHandler(request);
if (handler != null) {
return handler;
}
}
}
return null;
}
还有BeanDefinitionParserDelegate
模板模式
在Spring的AbstractApplicationContext.java中,refresh()是典型的模板模式,代码如下
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
//1.调用容器准备刷新的方法,获取容器的当时时间,同时给容器设置同步标志
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
//2.告诉子类启动refreshBeanFactory()方法,Bean定义资源文件的载入,从子类的refreshBeanFactory()方法启动
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
//3.为BeanFactory配置容器特性,例如类加载器、事件处理等
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
还有JdbcTemplate、HttpServlet
适配器模式
兼容转换头,如AdvisorAdapter、HandlerAdapter
boolean supportsAdvice(Advice advice);
MethodInterceptor getInterceptor(Advisor advisor);
装饰器模式
包装,同宗同源,如BufferdReader、InputStream、OutputStream、HttpHeadResponseDecorator
public class BufferedReader extends Reader {
//...
public BufferedReader(Reader in, int sz) {
super(in);
if (sz <= 0)
throw new IllegalArgumentException("Buffer size <= 0");
this.in = in;
cb = new char[sz];
nextChar = nChars = 0;
}
观察者模式
任务完成时通知,如ContextLoaderListener