5.设计模式-工厂方法模式

定义:定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。

简单工厂模式

需求

一个大学生,以学雷锋做好事的名义去帮助老人做事。

代码

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

typedef struct Leifeng
{
    void (*sweep)();
    void (*wash)();
    void (*buyRice)();
} Leifeng;

void Sweep() {
    printf("扫地\n");
}
void Wash() {
    printf("洗衣\n");
}
void BuyRice() {
    printf("买米\n");
}

Leifeng *ConstructLeiFeng() {
    Leifeng *obj = (Leifeng *)malloc(sizeof(Leifeng));
    obj->sweep = Sweep;
    obj->wash = Wash;
    obj->buyRice = BuyRice;
    return obj;
}

// 学雷锋
typedef struct Undergradute {
    Leifeng base;
} Undergradute;
typedef struct Volunteer {
    Leifeng base;
} Volunteer;

Undergradute *ConstructGraduate() {
    Undergradute *obj = (Undergradute *)malloc(sizeof(Undergradute));
    obj->base.sweep = Sweep;
    obj->base.wash = Wash;
    obj->base.buyRice = BuyRice;
    return obj;
}
Volunteer *ConstructVolunteer() {
    Volunteer *obj = (Volunteer *)malloc(sizeof(Volunteer));
    obj->base.sweep = Sweep;
    obj->base.wash = Wash;
    obj->base.buyRice = BuyRice;
    return obj;
}

typedef struct XueLeifengFactory {
    Leifeng *(*createLeiFeng)();
} XueLeifengFactory;

Leifeng *CreateLeifeng() {
    return ConstructLeiFeng();
}
Leifeng *CreateUndergraduate() {
    return (Leifeng *)ConstructGraduate();
}
Leifeng *CreateVoluteer() {
    return (Leifeng *)ConstructVolunteer();
}

客户端:

c 复制代码
int main() {
    XueLeifengFactory factory = {CreateUndergraduate};
    Leifeng *student = factory.createLeiFeng();
    student->sweep();
    student->wash();
    student->buyRice();
    free(student);
    return 0;
}

UML图

总结

  • 工厂方法模式相比简单工厂模式的优点?
    简单工厂模式在新增加功能时,需要修改工厂类,违背了开闭原则。工厂方法使一个类的实例化延迟到其子类,新增功能时增加一个工厂子类即可。缺点是由于每加一个产品,就需要加一个产品工厂的接口,增加了额外的开发量。
相关推荐
nnsix11 小时前
设计模式 - 建造者模式 笔记
笔记·设计模式·建造者模式
cui178756812 小时前
矩阵拼团 + 复购拼团:新零售最稳的复购模式,规则简单
大数据·人工智能·设计模式·零售
百珏12 小时前
[灰度发布]:全链路透传组件:APM、自研方案与 Java Agent 的实现取舍
后端·设计模式·架构
likerhood14 小时前
设计模式 · 享元模式(Flyweight Pattern)java
java·设计模式·享元模式
AI大法师15 小时前
从 Adobe 焕新看品牌系统升级:Logo、主色、字体与产品体验如何重新对齐
大数据·人工智能·adobe·设计模式
贵慜_Derek15 小时前
《从零实现 Agent 系统》连载 03|控制循环:感知—决策—行动—反思
人工智能·设计模式·架构
nnsix16 小时前
设计模式 - 原型模式 笔记
笔记·设计模式·原型模式
nnsix16 小时前
设计模式 - 适配器模式 笔记
笔记·设计模式·适配器模式
asdfg125896316 小时前
一文理解软件开发中的“设计模式”
java·设计模式·软件开发
云飞云共享云桌面17 小时前
SolidWorks 服务器通过云飞云共享云桌面10人研发共享方案
运维·服务器·3d·设计模式·电脑