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

相关推荐
阿波罗尼亚16 小时前
Head First设计模式(十四) 设计原则 其他的模式
设计模式
山风wind19 小时前
设计模式-责任链模式:让请求在链条中流动直到被处理
设计模式·责任链模式
invicinble20 小时前
设计模式全局预览,以及为什么会
设计模式
小股虫21 小时前
让系统“杀不死”:同步与异步场景下的弹性设计模式手册
分布式·微服务·设计模式·架构·团队建设·方法论
山风wind1 天前
设计模式:状态模式详解-让对象的行为随状态改变而改变
设计模式·状态模式
__万波__1 天前
二十三种设计模式(十八)--中介者模式
java·设计模式·中介者模式
自由生长20241 天前
设计模式和设计原则-中高级架构思路-面向接口编程
设计模式
大厂技术总监下海2 天前
为何顶尖科技公司都依赖它?解码 Protocol Buffers 背后的高性能、可演进设计模式
分布式·设计模式
EnzoRay2 天前
代理模式
设计模式
weixin_478433322 天前
iluwatar 设计模式
java·开发语言·设计模式