1. 程式人生 > 實用技巧 >靜態與動態工廠

靜態與動態工廠

例項

/**
 * 靜態工廠
 * @date 2020.04.01
 */
public class ExternalBeanStaticFactory {
    private static OkHttpClient OkHttpClient;
    public static OkHttpClient getInstance() {
        if (OkHttpClient == null) {
            OkHttpClient = new OkHttpClient.Builder().build();
        }
        return OkHttpClient;
    }
}
/**
 * 動態工廠
 * @author cxy
 * @date 2020.04.01
 */
public class ExternalBeanFactory {
    private OkHttpClient OkHttpClient;
    public OkHttpClient getInstance() {
        if (OkHttpClient == null) {
            OkHttpClient = new OkHttpClient.Builder().build();
        }
        return OkHttpClient;
    }
}
<!-- 靜態工廠 -->
<bean class="net.web.ExternalBeanStaticFactory" factory-method="getInstance" id="okHttpClientStatic"></bean>

<!-- 動態工廠 -->
<bean class="net.web.ExternalBeanFactory" id="ExternalBeanFactory"/>
<bean class="okhttp3.OkHttpClient" factory-bean="ExternalBeanFactory
" factory-method="getInstance" id="okHttpClient"></bean>

可以看到,靜態工廠的方法多了 static 關鍵字,而動態工廠就對了個bean 配置,看到這裡我們來總結一下:

  • 邏輯程式碼和配置方式的區別(這也是CSDN看到最多的關於這兩者的解釋)
  • 動態工廠需要更多的記憶體(達到一定的併發)