项目中为什么要使用工厂模式呢?
?
#include <iostream>
#include <string>
class Product {
public:
virtual void use() = 0;
};
class ConcreteProduct1 : public Product {
public:
void use() override {
std::cout << "Using ConcreteProduct1." << std::endl;
}
};
class ConcreteProduct2 : public Product {
public:
void use() override {
std::cout << "Using ConcreteProduct2." << std::endl;
}
};
class Factory {
public:
virtual Product* createProduct(const std::string& type) = 0;
};
class ConcreteFactory : public Factory {
public:
Product* createProduct(const std::string& type) override {
if (type == "type1") {
return new ConcreteProduct1();
} else if (type == "type2") {
return new ConcreteProduct2();
} else {
throw std::invalid_argument("Invalid product type.");
}
}
};
客户端代码调用生成具体工厂
int main() {
ConcreteFactory factory;
Product* product = factory.createProduct("type1");
product->use(); // 输出 "Using ConcreteProduct1."
delete product; // 不要忘记释放内存!
return 0;
}
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??