提供一个创建一系列相关或相互依赖对象的接口,而无须指定它们具体的类。
抽象工厂接口 IFactory 包含所有产品创建的抽象方法。而 ConcreteFactory* 就是具体的工厂。为创建不同的产品对象,客户端应使用不同的具体工厂。
#include <iostream>
#include <memory>
/* 抽象产品类A */
class VProductA {
public:
virtual void showFeature() const = 0;
virtual ~VProductA() = default;
};
/* 具体产品类 A1 */
class ConcreteProductA1 final : public VProductA {
public:
void showFeature() const override {
std::cout << "Concrete Product A1 here\n";
}
~ConcreteProductA1() = default;
};
/* 具体产品类 A2 */
class ConcreteProductA2 final : public VProductA {
public:
void showFeature() const override {
std::cout << "Concrete Product A2 here\n";
}
~ConcreteProductA2() = default;
};
/* 抽象产品类B */
class VProductB {
public:
virtual void showFeature() const = 0;
virtual ~VProductB() = default;
};
/* 具体产品类 B1 */
class ConcreteProductB1 final : public VProductB {
public:
void showFeature() const override {
std::cout << "Concrete Product B1 here\n";
}
~ConcreteProductB1() = default;
};
/* 具体产品类 B2 */
class ConcreteProductB2 final : public VProductB {
public:
void showFeature() const override {
std::cout << "Concrete Product B2 here\n";
}
~ConcreteProductB2() = default;
};
/* 抽象工厂 */
class VFactory {
public:
virtual std::unique_ptr<VProductA> CreateProductA() = 0;
virtual std::unique_ptr<VProductB> CreateProductB() = 0;
~VFactory() = default;
};
/* 具体工厂1 */
class Factory1 final : public VFactory {
public:
std::unique_ptr<VProductA> CreateProductA() {
return std::make_unique<ConcreteProductA1>();
}
std::unique_ptr<VProductB> CreateProductB() {
return std::make_unique<ConcreteProductB1>();
}
~Factory1() = default;
};
/* 具体工厂2 */
class Factory2 final : public VFactory {
public:
std::unique_ptr<VProductA> CreateProductA() {
return std::make_unique<ConcreteProductA2>();
}
std::unique_ptr<VProductB> CreateProductB() {
return std::make_unique<ConcreteProductB2>();
}
~Factory2() = default;
};
auto main() -> int {
std::unique_ptr<VFactory> fac = std::make_unique<Factory1>();
auto productA = fac->CreateProductA();
auto productB = fac->CreateProductB();
productA->showFeature();
productB->showFeature();
fac.reset(new Factory2);
std::cout << '\n';
productA = fac->CreateProductA();
productB = fac->CreateProductB();
productA->showFeature();
productB->showFeature();
return 0;
}