设计模式练习(二) 简单工厂模式

设计模式练习(二) 简单工厂模式

题目描述

小明家有两个工厂,一个用于生产圆形积木,一个用于生产方形积木,请你帮他设计一个积木工厂系统,记录积木生产的信息。

输入描述

输入的第一行是一个整数 N(1 ≤ N ≤ 100),表示生产的次数。

接下来的 N 行,每行输入一个字符串和一个整数,字符串表示积木的类型。积木类型分为 "Circle" 和 "Square" 两种。整数表示该积木生产的数量

输出描述

对于每个积木,输出一行字符串表示该积木的信息。

输入示例
复制代码
3
Circle 1
Square 2
Circle 1
输出示例
复制代码
Circle Block
Square Block
Square Block
Circle Block

code:

cc 复制代码
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <memory>
 
using namespace std;
 
class Block
{
public:
    virtual ~Block() {}
    virtual std::string GetBlockInfo() const = 0;
};
 
class CircleBlock : public Block
{
public:
    std::string GetBlockInfo() const override
    {
        return "Circle Block";
    }
};
 
class SquareBlock : public Block
{
public:
    std::string GetBlockInfo() const override
    {
        return "Square Block";
    }
};
 
class BlockFactory
{
public:
    static std::unique_ptr<Block> CreateBlock(const std::string &type)
    {
        if (type == "Circle")
        {
            return std::make_unique<CircleBlock>();
        }
        else if (type == "Square")
        {
            return std::make_unique<SquareBlock>();
        }
        return nullptr;
    }
};
 
int main()
{
    int N;
    std::cin >> N;
    for (int i = 0; i < N; ++i)
    {
        std::string type;
        int quantity;
        std::cin >> type >> quantity;
 
        for (int j = 0; j < quantity; ++j)
        {
            std::unique_ptr<Block> block = BlockFactory::CreateBlock(type);
            if (block)
            {
                std::cout << block->GetBlockInfo() << std::endl;
            }
        }
    }
    return 0;
}

工程模式是创建模式

可以看到积木是不变的,为一个接口;其变化的是方形积木和圆形积木,是积木接口的具体实现

开闭原则:对扩展开放,修改关闭;不修改已有代码,灵活地增加新的产品类

相关推荐
Peregrine98 小时前
C++ - > 类和对象
java·c++·算法
‎ദ്ദിᵔ.˛.ᵔ₎9 小时前
c++11:fuction包装器
开发语言·c++
霍霍的袁10 小时前
【C++】哈希表实现指南:从原理到开放定址法、链地址法的实现
c++·学习·哈希算法·散列表·visual studio
WL学习笔记11 小时前
类和对象(下)
c++·类和对象
傲世仙尊12 小时前
拷贝构造-传值传参的连锁反应与隐式函数的三个局限
c++
垆边人似月.12 小时前
华为机试题 :最大数
c++·算法·华为
方便面不加香菜12 小时前
C++ 关于多态的知识点讲解
开发语言·c++
jimy113 小时前
C++ 类成员函数的内联定义(inline)详解
开发语言·c++
范中勤13 小时前
技术文档:模型工厂 `llm_provider` / `llm_use` 分层设计
设计模式·langchain·架构设计·模型工厂·llm_provider
sanqima13 小时前
CreateThread、_beginthreadex、AfxBeginThread三种线程创建的区别与联系
c++·tls·线程创建