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

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

题目描述

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

输入描述

输入的第一行是一个整数 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;
}

工程模式是创建模式

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

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

相关推荐
持力行3 小时前
从C struct到C++中的class
c语言·c++
GIS阵地6 小时前
QgsRasterDataProvider 完整详解(QGIS 3.40.13 C++)
开发语言·c++·qt·开源软件·qgis
ttod_qzstudio8 小时前
【软考设计模式】备忘录模式:对象状态的捕获与无损恢复精讲
设计模式·备忘录模式
ttod_qzstudio8 小时前
【软考设计模式】责任链模式:请求传递的多级处理与发送接收解耦精讲
设计模式·责任链模式
charlie1145141918 小时前
Cinux: 为大内核铺路
开发语言·c++·操作系统·现代c++
2501_914245938 小时前
C语言设计模式详解:从理论到实践的完整指南
c语言·开发语言·设计模式
米罗篮11 小时前
矩阵快速幂 (Exponentiation By Squaring Applied To Matrices)
c++·线性代数·算法·矩阵
肖爱Kun11 小时前
C++设计策略模式
开发语言·c++·策略模式
炸膛坦客12 小时前
单片机/C/C++八股:(二十四)编译文件( .bin 和 .hex ,包括 .elf 和 .axf )
c语言·c++·单片机
CaffeinePro12 小时前
四⼤极简架构原则KISS/DRY/YAGNI/LOD
设计模式·架构