C++ 工厂模式

8.9.2 工厂模式

对类实例化的过程提供一层static函数封装, 本质上等价于类指针;

使用步骤:

//第一步,定义一个抽象产品类
class Product {
public:
    virtual void operation() = 0;
};

//第二步,实现具体产品类
class ConcreteProductA : public Product {
public:
    void operation() override {
        // 具体产品A的操作实现
    }
};

class ConcreteProductB : public Product {
public:
    void operation() override {
        // 具体产品B的操作实现
    }
};

//第三步,工厂类
class Factory {
public:
    // 工厂方法,根据不同的条件创建不同的具体产品对象
    static Product* createProduct(std::string type) {
        if (type == "A") {
            return new ConcreteProductA();
        } else if (type == "B") {
            return new ConcreteProductB();
        } else {
            return nullptr;
        }
    }
};

示例代码:

#include <iostream>
#include <string>

// 抽象产品类
class Product {
public:
    virtual void operation() = 0;
};

// 具体产品类A
class ConcreteProductA : public Product {
public:
    void operation() override {
        std::cout << "ConcreteProductA operation." << std::endl;
    }
};

// 具体产品类B
class ConcreteProductB : public Product {
public:
    void operation() override {
        std::cout << "ConcreteProductB operation." << std::endl;
    }
};

// 工厂类
class Factory {
public:
    // 工厂方法,根据输入参数创建具体产品对象
    static Product* createProduct(std::string type) {
        if (type == "A") {
            return new ConcreteProductA();
        } else if (type == "B") {
            return new ConcreteProductB();
        } else {
            return nullptr;
        }
    }
};

int main() {
    // 使用工厂类创建产品对象
    Product* productA = Factory::createProduct("A");
    if (productA) {
        productA->operation();  // 输出:ConcreteProductA operation.
    }

    Product* productB = Factory::createProduct("B");
    if (productB) {
        productB->operation();  // 输出:ConcreteProductB operation.
    }

    delete productA;
    delete productB;

    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值