实现
c
复制代码
#include <iostream>
#include <memory>
// 抽象产品类
class Product {
public:
virtual ~Product() {}
virtual void Operation() const = 0;
};
// 具体产品 类A
class ConcreteProductA : public Product {
public:
virtual void Operation() const override {
std::cout << "Product A" << std::endl;
}
};
// 具体产品 类B
class ConcreteProductB : public Product {
public:
virtual void Operation() const override {
std::cout << "Product B" << std::endl;
}
};
enum class ProductType: uint8_t {
ProductA = 0,
ProductB = 1
};
// 工厂类
class Factory {
public:
Product *CreateProduct(enum ProductType type) const {
switch(type) {
case ProductType::ProductA:
return new ConcreteProductA;
case ProductType::ProductB:
return new ConcreteProductB;
default:
throw std::invalid_argument("Invalid product type");
}
}
};
int main(int argc, char **argv)
{
Factory factory;
// 创建产品 A
ConcreteProductA *productA = reinterpret_cast<ConcreteProductA*>(factory.CreateProduct(ProductType::ProductA));
productA->Operation();
delete productA;
// 创建产品 B
ConcreteProductB* productB = reinterpret_cast<ConcreteProductB*>(factory.CreateProduct(ProductType::ProductB));
productB->Operation();
delete productB;
return 0;
}
c
复制代码
#include <iostream>
#include <memory>
// 抽象产品类
class Product {
public:
virtual ~Product() {}
virtual void Operation() const = 0;
};
// 具体产品 类A
class ConcreteProductA : public Product {
public:
virtual void Operation() const override {
std::cout << "Product A" << std::endl;
}
};
// 具体产品 类B
class ConcreteProductB : public Product {
public:
virtual void Operation() const override {
std::cout << "Product B" << std::endl;
}
};
// 抽象工厂类
class Factory {
public:
virtual ~Factory(){}
virtual Product *CreateProduct() = 0;
};
// A类工厂
class ProductAFactory: public Factory {
public:
virtual Product *CreateProduct() override {
return new ConcreteProductA();
}
};
// B类工厂
class ProductBFactory: public Factory {
public:
virtual Product *CreateProduct() override {
return new ConcreteProductB();
}
};
int main(int argc, char **argv)
{
Factory *a_factory = new ProductAFactory();
Factory *b_factory = new ProductBFactory();
auto a_product = a_factory->CreateProduct();
auto b_product = b_factory->CreateProduct();
a_product->Operation();
b_product->Operation();
delete a_product;
delete b_product;
delete a_factory;
delete b_factory;
return 0;
}