# 2.1 Simple Factory

![](/files/-M523vAubowptzerEzlf)

* 關於簡單工廠, 大概有以下幾點特性:
  * 可用來創造介面、抽象類別或著是普通類別的實例
  * 通常把簡單工廠類別實作成一個util class,直接使用其靜態方法即可, 即簡單工廠的方法通常是靜態的, 故也稱作靜態工廠
  * 理論上簡單工廠可以用來構築任何物件, 故又稱萬能工廠
  * 關於簡單工廠建立之物件的scope, 建議控制在一個獨立的元件級別或著是一個模組的級別
* 簡單工廠的內部核心實作是要選擇合適的實作類別來建立實例物件

以下是簡單的範例:

Api介面的部分:

```java
package idv.design.pattern.simpleFactory.example2;

/**
 * Created by Carl on 2015/9/8.
 */
public interface Api {

    public void callApi(String s);

}
```

Api介面的不同實作1:

```java
package idv.design.pattern.simpleFactory.example2;

/**
 * Created by Carl on 2015/9/8.
 */
public class ApiImpl1 implements Api {

    public void callApi(String s) {
        System.out.println("The content from impl1 is: " + s);
    }

}
```

Api介面的不同實作2:

```java
package idv.design.pattern.simpleFactory.example2;

/**
 * Created by Carl on 2015/9/8.
 */
public class ApiImpl2 implements Api {

    public void callApi(String s) {
        System.out.println("The content from impl2 is: " + s);
    }

}
```

可以依據傳入的參數來選擇實作的Factory:

```java
package idv.design.pattern.simpleFactory.example2;

/**
 * Created by Carl on 2015/9/8.
 */
public class Factory {

    public static Api createApi(int condition) {

        Api api = null;
        if(condition == 1) {
            api = new ApiImpl1();
        } else if(condition == 2) {
            api = new ApiImpl2();
        }
        return api;

    }

}
```

Client的部分:

```java
package idv.design.pattern.simpleFactory.example2;

/**
 * Created by Carl on 2015/9/8.
 */
public abstract class Client {

    public static void main(String[] args) {
        Api api = Factory.createApi(1);
        api.callApi("With simple factory.");
    }

}
```

關於Simple Factory Pattern的範例, 可參考[這邊](https://github.com/yotsuba1022/design-pattern/tree/master/src/main/java/idv/design/pattern/simpleFactory)

* 可配置的簡單工廠: 使用反射(reflection)機制加上配置文件, 來實現添加新的實作類別後, 不需要修改程式, 就能把這個新的實作類別加入程式中
* 簡單工廠的優缺點
  * 幫助封裝
  * 解耦
  * 可能增加客戶端的複雜度
  * 不方便擴展子工廠
* **簡單工廠的本質: 選擇實作**
* 何時選用簡單工廠
  * 若想要完全封裝隔離具體實作, 讓外部只能通過介面來操作封裝體, 那就可以考慮此模式, 讓客戶通過工廠來獲取相應的介面而無需關心具體實作
  * 若想要把對外建立物件的職責集中管理和控制, 即可選擇簡單工廠, 一個簡單工廠可以建立很多的且不相關的物件, 可以把對外建立物件的職責集中到一個簡單工廠中, 進而實現集中管理與控制


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://clu.gitbook.io/design-pattern/21-simple-factory.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
