编程语言
首页 > 编程语言> > 【c++设计模式】工厂模式

【c++设计模式】工厂模式

作者:互联网

工厂模式:工厂模式提供了一种创建对象的方式。首先,定义抽象的对象(产品)以及具体对象(产品)细节,其次,使用抽象工厂提供的公共借口来完成对象的创建。

UML:

代码案例:

class Product
{
public:
    Product() {}
    virtual ~Product() {}
    virtual double GetResult() = 0;
    void setA(double a) {
        this->mNumberA = a;
    }
    void setB(double b) {
        this->mNumberB = b;
    }
protected:
    double mNumberA;
    double mNumberB;
};


// 加法运算类
class ProductA :public Product
{
public:
    ProductA() {}
    ~ProductA() {}
    virtual double GetResult()
    {
        return (mNumberA + mNumberB);
    }
};



class AbstractFactory
{
public:
    AbstractFactory() {}
    virtual ~AbstractFactory() {}
    virtual Product* CreateProduct() = 0; // 声明一个专门用来创建对象的公共接口,具体工厂类继承并重写
};


class FactoryA :public AbstractFactory
{
public:
    FactoryA() {}
    ~FactoryA() {}

    // 重写虚函数CreateProduct()
    virtual Product* CreateProduct()
    {
        return (new ProductA());
    }
};


int main() {
    AbstractFactory* operFactory = nullptr;
    Product* oper = nullptr;
    operFactory = new FactoryA();
    oper = operFactory->CreateProduct();
    oper->setA(2.5);
    oper->setB(5);
    cout <<oper->GetResult();
}

 

标签:oper,Product,double,virtual,工厂,c++,AbstractFactory,设计模式,public
来源: https://www.cnblogs.com/jasonhuustc/p/16373067.html