設計模式——工廠模式

問題描述:
使用工廠模式實現簡單計算器的加減乘數功能。

github地址:https://github.com/lining91/FactoryPattern2

    工廠方法模式,定義了一個用於創建對象的接口,封裝對象的創建,讓子類決定實例化哪一個類。工廠方法使一個類的實例化延遲到其子類中。

**與簡單工廠的區別:**

    簡單工廠模式的優點是工廠類中包含了必要的邏輯判斷,根據增加需求來動態的實例化相關的類,去除了與具體產品的依賴。
    在簡單工廠模式中,當增加需求時,需要修改原有的工廠類,增加新的類,對擴展開放了,對修改也開放了,違背了開放-封閉原則。
    工廠模式中,當增加需求時,不需要修改原有的工廠類,只需要增加此類需求的類和相應的工廠類即可。符合開放-封閉原則。




**代碼如下:**
操作類如下
//  操作基類
class Operation{
public:
    virtual int GetResult( int n1, int n2 ) = 0;
};


//  加減乘數類
class OperationAdd : public Operation{
public:
    virtual int GetResult(int n1, int n2)
    {
        return n1 + n2;
    }
};


class OperationSub : public Operation{
public:
    virtual int GetResult(int n1, int n2)
    {
        return n1 - n2;
    }
};

class OperationMul : public Operation{
public:
    virtual int GetResult(int n1, int n2)
    {
        return n1 * n2;
    }
};

class OperationDiv : public Operation{
public:
    virtual int GetResult(int n1, int n2)
    {
        if (n2 == 0)
            throw "除數不能爲0!";
        return n1 / n2;
    }
};
工廠抽象類和工廠具體類:
//  抽象工廠類
class IFactory
{
public:
    virtual Operation* CreateOperation() = 0;
};


//  具體工廠類
class AddFactory : public IFactory
{
public:
    Operation* CreateOperation()
    {
        return new OperationAdd();
    }
};

class SubFactory : public IFactory
{
public:
    Operation* CreateOperation()
    {
        return new OperationSub();
    }
};

class MulFactory : public IFactory
{
public:
    Operation* CreateOperation()
    {
        return new OperationMul();
    }
};

class DivFactory : public IFactory
{
public:
    Operation* CreateOperation()
    {
        return new OperationDiv();
    }
};
main 函數:
void main()
{
    int n1 = 33;
    int n2 = 52;

    //  創建具體操作工廠類,如果需要修改新的計算方式,需要重新生成該類
    IFactory* pFactory = new MulFactory();
    if ( pFactory == NULL )
        return;

    Operation* pOpe = pFactory->CreateOperation();
    if (pOpe == NULL)
        return;

    try{
        int nResult = pOpe->GetResult(n1, n2);
        cout << n1 << " * " << n2 << " is " << nResult << endl;
    }
    catch(char* pErr)
    {
        cout << pErr << endl;
    }
    delete pOpe;
    pOpe = NULL;
    delete pFactory;
    pFactory = NULL;

    system("pause");
}

運行結果如下:
這裏寫圖片描述

當需要修改乘法運算爲“+”運算時,只需要重新生成main函數中的IFactory* pFactory實例。降低代碼的耦合度,對其餘代碼沒有影響。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章