自学内容网 自学内容网

设计模式--创建型

请添加图片描述

实现

#include <iostream>
#include <memory>

// 抽象产品类
class Product {
  public:
      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;
}

原文地址:https://blog.csdn.net/xxboy61/article/details/140674709

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!