WebContextFactory是工厂,方法都是静态的,持有一个Builder实例和Builder的接口
WebContextBuilder是产品的制造机器,他的实现类可以自定义,不同的实现类,对应不同的产品制造方式。
WebContext 是产品
WebContextFactory对WebContextBuilder进行了封装,让购买者和产品的生产进行解耦
- public class WebContextFactory
- {
- public static WebContext get()
- {
- if (builder == null)
- {
- log.warn("Missing WebContextBuilder. Is DWR setup properly?");
- return null;
- }
-
- return builder.get();
- }
-
-
- private static WebContextBuilder builder = null;
-
-
- public static void attach(Container container)
- {
- WebContextFactory.builder = container.getBean(WebContextBuilder.class);
- }
-
-
- public interface WebContextBuilder
- {
-
- WebContext get();
-
-
- void engageThread(Container container, HttpServletRequest request, HttpServletResponse response);
-
-
- void disengageThread();
- }
-
-
-
-
- private static final Log log = LogFactory.getLog(WebContextFactory.class);
- }
DwrServlet 类webContextBuilder 的使用
doPost方法里使用构建器webContextBuilder 负责本线程webContext对象的生产和销毁
在后面Handler方法里使用工厂WebContextFactory生产产品
- public void init(ServletConfig servletConfig) throws ServletException
- {
- super.init(servletConfig);
-
- try
- {
- StartupUtil.logStartup(getClass().getSimpleName(), servletConfig);
-
-
- container = createContainer(servletConfig);
-
- webContextBuilder = container.getBean(WebContextBuilder.class);
-
-
- configureContainer(container, servletConfig);
- }
- catch (ServletException ex)
- {
- throw ex;
- }
- catch (Exception ex)
- {
- log.fatal("init failed", ex);
- throw new ServletException(ex);
- }
- finally
- {
- if (webContextBuilder != null)
- {
- webContextBuilder.disengageThread();
- }
- }
- }
- @Override
- public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
- {
- try
- {
-
-
-
- webContextBuilder.engageThread(container, request, response);
-
-
- UrlProcessor processor = container.getBean(UrlProcessor.class);
- processor.handle(request, response);
- }
- finally
- {
- webContextBuilder.disengageThread();
- }
- }