简单工厂模式是属于创建型模式,又叫做静态工厂方法(Static Factory Method)模式,实质是由一个工厂类根据传入的参数,动态决定应该创建哪一个产品类(这些产品类继承自一个父类或接口)的实例。

该模式中包含三个角色:

工厂(Factory)角色

简单工厂模式的核心,它负责实现创建所有实例的内部逻辑。工厂类的创建产品类的方法可以被外界直接调用,创建所需的产品对象。

抽象产品(Product)角色

简单工厂模式所创建的所有对象的父类,它负责描述所有实例所共有的公共接口。

具体产品(Concrete Product)角色

是简单工厂模式的创建目标,所有创建的对象都是充当这个角色的某个具体类的实例。

优点:外界不需要知道具体对象如何创建和组织,明确了各自的职责;

缺点:违反了高内聚的原则,将全部创建逻辑集中到了一个工厂类中;它所能创建的类只能是事先考虑到的,如果需要添加新的类,则就需要改变工厂类了。

UML类图:

大话设计模式第1章——简单工厂模式

C++实现:

#include <iostream>

using namespace std;
//算法抽象类
class OPeration
{
public:
    double GetA()
    {
        return m_dA;
    }

    double GetB()
    {
        return m_dB;
    }

    virtual double GetResult()
    {
        double dResult = 0;
        return dResult;
    }

    void SetA(double dA)
    {
        m_dA = dA;
    }

    void SetB(double dB)
    {
        m_dB = dB;
    }

protected:
    double m_dA;
    double m_dB;
};

class OperationAdd:public OPeration
{
public:
    double GetResult()
    {
        double dResult = m_dA + m_dB;
        return dResult;
    }
};

class OperationSub:public OPeration
{
public:
    double GetResult()
    {
        double dResult = m_dA - m_dB;
        return dResult;
    }
};

class OperationMult:public OPeration
{
public:
    double GetResult()
    {
        double dResult = m_dA * m_dB;
        return dResult;
    }
};

class OperationDivi:public OPeration
{
public:
    double GetResult()
    {
        if(0 == m_dA)
        {
            return 0;
        }
        double dResult = m_dA / m_dB;
        return dResult;
    }
};
//工厂类
class OPerationFactory
{
public:
    OPeration *CreateOperation(char type)
    {
        OPeration *oper = NULL;
        switch(type)
        {
        case '+':
            oper = new OperationAdd;
            break;
        case '-':
            oper = new OperationSub;
            break;
        case '*':
            oper = new OperationMult;
            break;
        case '/':
            oper = new OperationDivi;
            break;
        }
        return oper;
    }
};

int main()
{
    OPerationFactory factory;
    OPeration *oper = factory.CreateOperation('*');
    oper->SetA(123);
    oper->SetB(321);

    cout << oper->GetResult() << endl;

    if(oper != NULL)
    {
        delete oper;
        oper = NULL;
    }
    return 0;
}

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-06
  • 2021-06-10
  • 2022-12-23
  • 2021-08-02
  • 2021-04-23
猜你喜欢
  • 2021-09-15
  • 2021-06-06
  • 2021-11-06
  • 2021-07-14
  • 2022-01-03
  • 2022-12-23
  • 2021-06-17
相关资源
相似解决方案