1.设计模式-简单工厂模式

读大话设计模式的笔记,通过C语言实现其中的代码

好代码特性:

  • 可维护:结构清晰,方便修改
  • 可复用:新功能也可使用老代码
  • 可扩展:老代码可以增加代码实现新功能
  • 灵活性:代码中的子功能可随意组合

大话设计模式一书中使用活字印刷术相比雕版印刷的创新类比,个人认为确实很形象。

示例场景

需求

"请用C++、Java、C#或VB.NET任意一种面向对象语言实现一个计算器控制台程序,要求输入两个数和运算符号,得到结果。"

需求分析

1.业务和界面分离

2.可能有增加运算方式的需要,代码需要增加运算方式方便

示例代码

c 复制代码
#include <stdio.h>
#include <stdlib.h>

typedef struct Operation{
    double numberA;
    double numberB;
    double (*GetResult)(struct Operation *);
} Operation;

// 依赖
double Add(Operation *op) {
    printf("%lf %lf\n", op->numberA, op->numberB);
    return op->numberA+op->numberB;
}
double Sub(Operation *op) {
    return op->numberA-op->numberB;
}
// 简单工厂
Operation *InitOperation(double numberA, double numberB, char operate) {
    Operation *res = (Operation *)malloc(sizeof(Operation));
    res->numberA = numberA;
    res->numberB = numberB;
    printf("%lf %lf %c\n", numberA, numberB, operate);
    switch(operate) {
        case '+': 
        res->GetResult = Add;
        break;
        case '-':
        res->GetResult = Sub;
        break;
        default:
        res->GetResult = NULL;
    }
    return res;
}

UML图

使用draw.io绘制

相关推荐
geovindu7 小时前
rust: Composite Pattern
开发语言·后端·设计模式·rust·组合模式
今年下半年9 小时前
【Spring Boot】多种存储文件(FastDFS / MinIO / 阿里云 OSS)接入设计说明(附源码)
spring boot·分布式·中间件·简单工厂模式·策略模式
YYYing.11 小时前
【设计模式系列 (七) 】桥接模式
c++·后端·设计模式·桥接模式
阿狗童鞋1 天前
设计模式实战指南
设计模式
电子科技圈1 天前
基于车载SerDes和OpenGMSL协议的SoC设计与验证:行业高频问题解析
设计模式·车载系统·软件构建·设计规范
ClinicTech2 天前
高速冷冻离心机的温控系统与安全保护逻辑解析
设计模式·架构·健康医疗·设计语言
GISMagic2 天前
3.《设计模式》:软件设计与解耦能力提炼
设计模式·ai coding
染指11102 天前
131.Agent-Agent设计模式-MAS多智能体系统(Multi-Agent-System)
人工智能·设计模式·langchain·agent·agents
ShyanZh2 天前
【Python3基础】13-Python 常用设计模式
开发语言·python·设计模式
YYYing.3 天前
【设计模式系列 (五) 】原型模式
开发语言·后端·设计模式·原型模式·c/c++