Abstract Factory模式

Abstract Factory模式_第1张图片

 

int main()

{

     CustomDialog* pDialog = new CustomDialog(new WindowsWidgetFactory());

     pDialog->ShowDialog();

 

     CustomDialog* pMacDialog = new CustomDialog(new MacWidgetFactory());

     pMacDialog->ShowDialog();

}

 

public CustomDialog
{
public:
    CustomDialog(IWidgetFactory* pFactory)
    {
        this->SetWidgetFactory(pFactory);
    }
    void SetWidgetFactory(IWidgetFactory* pFactory)
    {
        this->SetButton(pFactory->GetButton());
        this->SetTextField(pFactory->GetTextField());
    }
    void SetButton(IButton* pButton)
    {
        m_pButton = pButton;
    }
    void SetTextField(ITextField* pText)
    {
        m_pTextField = pText;
    }
    ...

    void ShowDialog(){}
private:
    IButton*  m_pButton;
    ITextField* m_pTextField;
}

Abstract Factory模式_第2张图片

在Abstract Factory模式中将具体的Product封装在具体Factory实现中,而客户仍只要面对Factory与Product的抽象介面,避免依赖于具体的Factory与Product,由于Factory封装了所必须的Product,所以要更换掉所有的元件,只要简单的抽换掉Factory就可以了,不用修改客户端的程式。

你可能感兴趣的:(abstract)