Design Patterns 1: Abstract Factory

提供一个界面(AbstractFactory),用于创建一系列相关(ProductA1/ProductB1 ProductA2/ProductB2...)的对象。

Design Patterns 1: Abstract Factory_第1张图片

struct AbstractProductA {};
struct ProductA1 : AbstractProductA {};
struct ProductA2 : AbstractProductA {};

struct AbstractProductB {};
struct ProductB1 : AbstractProductB {};
struct ProductB2 : AbstractProductB {};

struct AbstractFactory
{
    virtual AbstractProductA* CreateProductA() = 0;
    virtual AbstractProductB* CreateProductB() = 0;
};

struct ConcreteFactory1 : AbstractFactory
{
    AbstractProductA* CreateProductA() override { return new ProductA1; }
    AbstractProductB* CreateProductB() override { return new ProductB1; }
};

struct ConcreteFactory2 : AbstractFactory
{
    AbstractProductA* CreateProductA() override { return new ProductA2; }
    AbstractProductB* CreateProductB() override { return new ProductB2; }
};

int main()
{
    AbstractFactory* F1 = new ConcreteFactory1;
    AbstractFactory* F2 = new ConcreteFactory2;

    auto A1 = F1->CreateProductA();
    auto A2 = F2->CreateProductA();
    auto B1 = F1->CreateProductB();
    auto B2 = F2->CreateProductB();
}

 

你可能感兴趣的:(C++,Design,Patterns)