1. 簡單原廠模式簡介
簡單原廠模式(Simple Factory),又被稱為"靜態Factory 方法模式"。它屬於"建立模式"(建立對象的模式),並且是"Factory 方法"模式的一種特殊實現。
通常,我們利用簡單原廠模式來進行類的建立。例如,擷取線程池對象,就是通過簡單原廠模式來實現的。它的結構圖如下所示:
工廠:工廠是簡單原廠模式的核心,提供了對外介面。用戶端或其它程式要擷取Product對象,都是通過Factory的介面來擷取的。
抽象產品:抽象產品是(許多)不同產品抽象出來的。Product可以是介面或者抽象類別。
具體產品:工廠中返回的產品對象,實際上是通過ConcreteProduct來建立的。
2. 簡單原廠模式代碼模型
public class Factory { public static Product newInstance() { return new ConcreteProduct(); }}public abstract Product {}public class ConcreteProduct extends Product { public ConcreteProduct() {}}
模型的類圖
3.簡單原廠模式的實際應用
我們在寫一個Servlet處理用戶端請求的時候, 往往會一個Servlet處理多個商務邏輯, 比如:
protected void doPost(HttpServletRequest request, HttpServletResponse response) { String flag = request.getParameter("flag"); if(flag.equals("service1")) { service1(); }else if(flag.equals("service2")) { service2(); } ...}
以上是我們的Servlet處理多商務邏輯的常規方法, 寫一坨if else語句。一種比較好的辦法就是, 將請求的分發與Servlet分離, 讓Servlet只處理商務邏輯。我們把各種請求的Servlet看做產品類, javax.servlet.HttpServlet是產品父類, javax.servlet.Servlet是產品介面, 這樣我們定義一個ServletFactory, 在過濾器裡解析url請求並交給ServletFactory來處理就可以了。 這就是一個典型的簡單工廠應用。
@WebFilter("/TransRequest")public class TransRequest implements Filter{ private String servletName; @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest myRequest = (HttpServletRequest)request; //拿到請求的servlet名字, 這裡我們約定請求都是/servletName形式 String names[] = myRequest.getRequestURI().trim().split("/"); servletName = names[2]; if( servletName != null) { //以下是最典型的兩句簡單工廠的例子 Servlet servlet = ServletFactory.createServlet(servletName); servlet.service(request, response); }else chain.doFilter(request, response); }
每次來一個請求我們用工廠生產一個servlet, 這樣可以免去在xml配置大量的servlet路徑資訊比較方便。而且這樣也會使邏輯更加清晰, servlet僅僅就是在業務層處理業務。
工廠類如下:
public class ServletFactory { public static Servlet createServlet(String servletName) throws ServletException { if(servletName.equals("servletName1")) { return new Service1(); }else if(servletName.equals("servletName2")){ return new Service2(); }else{ throw new ServletException("No such servlet"); } }}
上面的工廠類雖然沒有拋開繁瑣的if else, 但是利用簡單工廠的思想仍然解決了一些問題。簡單工廠是非常簡單的一種算不上設計模式的設計模式, 解決的問題也很有限。 以上請求分發各大javaEE 架構都已實現, 例如Struts2, 當然架構不是用的簡單工廠。
4.總結
簡單原廠模式, 總結起來就是一個工廠類,一個產品介面(其實也可以是一個抽象類別,甚至一個普通的父類)和一群實現了產品介面的具體產品,而這個工廠類,根據傳入的參數去創造一個具體的實作類別,並向上轉型為介面作為結果返回。