架構探險筆記9-框架優化
阿新 • • 發佈:2018-12-13
目前的框架已具備IOC、AOP、MVC等特性,基本上一個簡單的WEB應用可以通過它來開發了。但或多或少還存在一些不足,需要優化的地方還很多,此外,還有一些更強大的功能需要不斷地補充進來。
優化Action引數
明確Action引數優化目標
對於某些Action方法,根本用不上Param引數,但框架需要我們必須提供一個Param引數,這樣未免有些勉強。
/** * 進入客戶端介面 */ @Action("get:/customer") public View index(Param param){ List<Customer> customerList = customerService.getCustomerList("");return new View("customer.jsp").addModel("customerList",customerList); }
這個Action方法根本就不需要Param引數,放在這裡確實有些累贅,我們得想辦法去掉這個引數,並且確保框架能夠成功地呼叫Action方法。
動手優化Action引數使用方式
修改框架程式碼來支援這個特性:
@WebServlet(urlPatterns = "/*",loadOnStartup = 0) public class DispatcherServlet extends HttpServlet { @Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { *** Param param = new Param(paramMap); //呼叫Action方法 Method actionMethod = handler.getActionMethod(); Object result = null;/*優化沒有引數的話不需要寫引數*/ if (param.isEmpty()){ //如果沒有引數 result = ReflectionUtil.invokeMethod(controllerBean,actionMethod); //就不傳引數 }else{ //有引數 result = ReflectionUtil.invokeMethod(controllerBean,actionMethod,param); //傳引數 } *** } }
當param.isEmpty()為true時,可以不將Param引數傳入Action方法中,反之則將Param引數傳入Action方法中。
因此,我們需要為Param類新增一個isEmpty()方法。
public class Param { private Map<String,Object> paramMap; *** /** * 驗證引數是否為空 * @return */ public boolean isEmpty(){ return CollectionUtil.isEmpty(paramMap); } }
所謂驗證引數是否為空,實際上是判斷Param中的paramMap是否為空。
一旦做了這樣的調整,我們就可以在Action方法中根據實際情況省略了Param引數了,就像這樣
/** * 進入客戶端介面 */ @Action("get:/customer") public View index(){ List<Customer> customerList = customerService.getCustomerList(""); return new View("customer.jsp").addModel("customerList",customerList); }
至此,Action引數優化完畢,我們可以根據實際情況自由選擇是否在Action方法中使用Param引數。這樣的框架更加靈活,從使用的角度來看也更加完美。
提示:框架的實現細節也許比較複雜,但框架的建立者一定要站在使用者的角度,儘可能的簡化框架的使用方法。注重細節並不斷優化,這是每個框架建立者的職責。