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;
}