簡單工廠模式 -- 其本質就是由工廠類根據外部因素去選擇的創建一個實例。 簡單工廠模式模型:介面IProduct + 工廠類Creator 介面和實現類: 工廠類: 左瀟龍大神在博客裡面提到了簡單工廠的的一些實際應用,我學習一下。(http://www.cnblogs.com/zuoxiaolong ...
簡單工廠模式 -- 其本質就是由工廠類根據外部因素去選擇的創建一個實例。
簡單工廠模式模型:介面IProduct + 工廠類Creator
介面和實現類:
public interface IProduct { public void printSomethingByType(); }
public class Product_A implements IProduct { public void printSomethingByType() { System.out.println("-----用戶one執行----"); } }
public class Product_B implements IProduct {
public void printSomethingByType() {
System.out.println("-----用戶two執行----");
}
}
工廠類:
public class Creator { public IProduct factory(String type) { if ("One".equals(type)) { return new Product_A(); } else if ("Two".equals(type)) { return new Product_B(); } else { System.out.println("沒有要找的類型"); return null; } } }
--------
左瀟龍大神在博客裡面提到了簡單工廠的的一些實際應用,我學習一下。(http://www.cnblogs.com/zuoxiaolong/p/pattern4.html)
在使用Strust2開發的時候,一般一個servlet只會處理一個具體的業務請求,隨著業務量的增加,會導致在web.xml裡面配置servlet的配置。
如果要實現將幾個業務處理整合到一個servlet中去:
protected void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException {
//我們加入一個操作的參數,來讓servlet做出不同的業務處理
String operation = req.getParameter("operation");
if(operation.equals("login")){
System.out.println("login");
}else if (operation.equals("register")) {
System.out.println("register");
}else if (operation.equals("loginout")) {
System.out.println("loginout");
}else {
throw new RuntimeException("invalid operation");
}
}
如果你的項目中出現了這種代碼結構,請務必想辦法去掉它,你完全可以儘量忘掉Java里還有elseif和swich
也可以將各個分支的業務邏輯拆分出來,成為一個相對的方法體。但是這樣又違背了"單一原則"。因為我們的servlet應該只是處理業務邏輯,而不應該還要負責與業務邏輯不相關的處理方法定位這樣的責任,這個責任應該交給請求方,原本在三個servlet分別處理登陸,註銷和註冊的時候,其實就是這樣的,作為請求方,只要是請求 LoginServlet,就說明請求的人是要登陸,處理這個請求的servlet不需要再出現有關判斷請求操作的代碼。
攔截器會攔截requestName,然後構建一個工廠類通過requestName來返回對應的實例!
---------------
後續我會研究一下springmvc 路由控制的源碼,看看是不是也有簡單工廠模式的實現。