Simple Factory Pattern:

提供產生物件的方法, 而無須關注實作內容, 其物件類型可為interface, abstract class, class

 
當類別內有多建構式存在且每個建構式無法清楚的說明其用途時, 可使用Simple Factory代替建構式, 在SimpleFactory中以清楚的方法名稱說明建構式的用途
這是我在專案遇到的情況, 我必須寫出1個Dialog, 此Dialog的元件在不同的情況下會有不同的組合, 如在A情況此dialog只有1個按鈕, 在B情況會有2個按鈕
一開始考慮使用建構式來決定產生何種dialog

package com.foxx.simplefactory;
import android.app.Dialog;
import android.content.Context;
import android.widget.Button;
import android.widget.TextView;
public class CustomDialog extends Dialog
{
    private String mDescription;
    private TextView mUpTextView;
    private TextView mDownTextView;
    private Button mUpButton;
    private Button mDownButton;
    /**
     * Used in one button
     */
    public CustomDialog(Context context, Button upButton) {
        super(context);
    }
    /**
     * Used in two button
     */
    public CustomDialog(Context context, Button upButton, Button downButton) {
        super(context);
    }
    /**
     * Used in one button and one description
     */
    public CustomDialog(Context context, Button upButton, String description) {
        super(context);
    }
}

 
CustomDialog的使用者除了從建構式的參數以及註解外, 無法了解建構式的使用方式(意圖), 為了解決這個情況我試著引入Simple Factory來修改

package com.foxx.simplefactory;
import android.content.Context;
import android.widget.Button;
public class CustomDialogFactory
{
    public static CustomDialog createOneButtonDialog(Context context, Button upButton)
    {
        return new CustomDialog(context, upButton);
    }
    public static CustomDialog createTwoButtonDialog(Context context, Button upButton,
            Button downButton)
    {
        return new CustomDialog(context, upButton, downButton);
    }
    public static CustomDialog createOneButtonOneDescriptionDialog(Context context,
            Button upButton, String description)
    {
        return new CustomDialog(context, upButton, description);
    }
}

 
使用者可根據Simple Factory的方法名稱選擇建立CustomDialog物件

package com.foxx.simplefactory;
import com.example.simplefactory.R;
import com.foxx.factorymethod.*;
public class MainActivity extends Activity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        CustomDialog oneButtonDialog = CustomDialogFactory.createOneButtonDialog(context, upButton);
        CustomDialog twoButtonDialog = CustomDialogFactory.createTwoButtonDialog(context, upButton, downButton);
        CustomDialog oneButtonOneDescriptionDialog =
        CustomDialogFactory.createOneButtonOneDescriptionDialog(context, upButton, description);
    }
}

 

Class Diagram

simplefactory_classdiagram