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绘制

相关推荐
咖啡八杯1 天前
GoF设计模式——中介者模式
java·后端·spring·设计模式
胡萝卜术2 天前
从“分数打架”到“排名投票”:为什么你的ChatBI必须用RRF?
算法·设计模式·面试
亦暖筑序3 天前
Java 8老系统Browser Agent实战:三层拦截把AI操作后台变成可审计流程
java·后端·设计模式
青禾网络5 天前
Web 前端如何接入 AI 音效生成:从零到可用的完整方案
人工智能·设计模式
ZJPRENO6 天前
吃透软件开发六大设计原则,告别烂代码
设计模式
咖啡八杯6 天前
GoF设计模式——命令模式
java·设计模式·架构
花椒技术6 天前
HJPusher / HJPlayer SDK 实践:我们为什么把直播推播链路拆成一套可复用能力
设计模式·harmonyos·直播
艺艺生辉7 天前
迭代器模式-"我也想被增强for循环"
设计模式
咖啡八杯8 天前
GoF设计模式——策略模式
java·后端·spring·设计模式