抽象工厂模式

#include <iostream>
#include <memory>

class ProductA {
public:
    virtual void show() = 0;
};

class ConcreteProductA1 : public ProductA {
public:
    void show() override { std::cout << "In ConcreteProductA1 show()." << std::endl; }
};

class ConcreteProductA2 : public ProductA {
public:
    void show() override { std::cout << "In ConcreteProductA2 show()." << std::endl; }
};

class ProductB {
public:
    virtual void show() = 0;
};

class ConcreteProductB1 : public ProductB {
public:
    void show() override { std::cout << "In ConcreteProductB1 show()." << std::endl; }
};

class ConcreteProductB2 : public ProductB {
public:
    void show() override { std::cout << "In ConcreteProductB2 show()." << std::endl; }
};

class AbstractFactory {
public:
    virtual std::unique_ptr<ProductA> createProductA() = 0;
    virtual std::unique_ptr<ProductB> createProductB() = 0;
};

class ConcrateFactory1 : public AbstractFactory {
public:
    std::unique_ptr<ProductA> createProductA() override { return std::make_unique<ConcreteProductA1>(); }
    std::unique_ptr<ProductB> createProductB() override { return std::make_unique<ConcreteProductB1>(); }
};

class ConcrateFactory2 : public AbstractFactory {
public:
    std::unique_ptr<ProductA> createProductA() override { return std::make_unique<ConcreteProductA2>(); }
    std::unique_ptr<ProductB> createProductB() override { return std::make_unique<ConcreteProductB2>(); }
};

int main(int argc, char *argv[]) {
    std::unique_ptr<AbstractFactory> f = std::make_unique<ConcrateFactory1>();
    std::unique_ptr<ProductA> pA1 = f->createProductA();
    pA1->show();
    std::unique_ptr<ProductB> pB1 = f->createProductB();
    pB1->show();
    f = std::make_unique<ConcrateFactory2>();
    std::unique_ptr<ProductA> pA2 = f->createProductA();
    pA2->show();
    std::unique_ptr<ProductB> pB2 = f->createProductB();
    pB2->show();
    return 1;
}

  

posted @ 2022-02-25 17:44  南乡水  阅读(16)  评论(0编辑  收藏  举报