本站首页    管理页面    写新日志    退出


«August 2025»
12
3456789
10111213141516
17181920212223
24252627282930
31


公告

戒除浮躁,读好书,交益友


我的分类(专题)

日志更新

最新评论

留言板

链接

Blog信息
blog名称:邢红瑞的blog
日志总数:523
评论数量:1142
留言数量:0
访问次数:9694586
建立时间:2004年12月20日




[编程感想]template method看基类设计的脆弱性
原创空间,  软件技术,  电脑与网络

邢红瑞 发表于 2007/7/4 22:38:29

 使用spring mvc的人做这段代码不会默认吧,AbstractController.java protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)   throws Exception {   // Form submission or new form to show?  if (isFormSubmission(request)) {   // Fetch form object from HTTP session, bind, validate, process submission.   try {    Object command = getCommand(request);    ServletRequestDataBinder binder = bindAndValidate(request, command);    BindException errors = new BindException(binder.getBindingResult());    return processFormSubmission(request, response, command, errors);   }   catch (HttpSessionRequiredException ex) {    // Cannot submit a session form if no form object is in the session.    if (logger.isDebugEnabled()) {     logger.debug("Invalid submit detected: " + ex.getMessage());    }    return handleInvalidSubmit(request, response);   }  }   else {   // New form to show: render form view.   return showNewForm(request, response);  } }我们做的实现就是, /**  * Template method. Subclasses must implement this.  * The contract is the same as for <code>handleRequest</code>.  * @see #handleRequest  */ protected abstract ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)     throws Exception;这就是典型的模板方法模式。记得2003年和JDC的人讨论java的设计时,感觉java类的派生设计的有问题,因为接口优先于继承,使用接口,最好就不要用类的继承了,当时有人反对,继承诞生了template method这个模式,大家马上得出一致结论,template method导致了基类设计的脆弱性,不稳定性,Framework的作者通常把主要逻辑写在Template Method 中。Template Method会调用若干Hook Method,Hook Method通常就是框架使用者的切入点。改变Hook Method,就可改变Template Method的行为。( 例如Servlet的doGet()/doPost() ),但是基类的修改也就是框架的修改,必然导致子类的重新编译,如果基类修改过于多,子类很可能重写。不过马上有人说微软的mfc不是使用Template Method吗,注意微软使用了Template Method,不应该说mfc的设计正确,地球上除了IBM目前没有微软的对手。一般情况是struts 0.9写的代码,在struts2.0下编译通不过,但是mfc程序,我当时使用MSC这不是IDE,使用mfc1.0写的程序,在vc6IDE,mfc4.2编译运行没有问题,著名开发工具的厂商Borland C++3.1的OWL的程序,不经修改在Borland C++4.5下编译一般通不过,这从侧面说明微软的mfc设计的完备,但是好日子到头了,从mfc7.0就是vc7.0开始微软已经开始不支持以前的mfc程序了,vc8.0用ATL重写CString,Template Method已经显示出他的弱点。如果一个项目是自己做以后又要自己维护的话,建议不要使用Template Method模式。


阅读全文(5649) | 回复(0) | 编辑 | 精华
 



发表评论:
昵称:
密码:
主页:
标题:
验证码:  (不区分大小写,请仔细填写,输错需重写评论内容!)



站点首页 | 联系我们 | 博客注册 | 博客登陆

Sponsored By W3CHINA
W3CHINA Blog 0.8 Processed in 0.078 second(s), page refreshed 144763991 times.
《全国人大常委会关于维护互联网安全的决定》  《计算机信息网络国际联网安全保护管理办法》
苏ICP备05006046号