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图

总结

  • 工厂方法模式相比简单工厂模式的优点?
    简单工厂模式在新增加功能时,需要修改工厂类,违背了开闭原则。工厂方法使一个类的实例化延迟到其子类,新增功能时增加一个工厂子类即可。缺点是由于每加一个产品,就需要加一个产品工厂的接口,增加了额外的开发量。
相关推荐
GISer_Jing6 小时前
智能体工具使用、规划模式
人工智能·设计模式·prompt·aigc
GISer_Jing6 小时前
AI Agent:学习与适应、模型上下文协议
人工智能·学习·设计模式·aigc
小马爱打代码8 小时前
MyBatis设计模式:构建者、工厂、代理模式
设计模式·mybatis·代理模式
月明长歌8 小时前
Javasynchronized 原理拆解:锁升级链路 + JVM 优化 + CAS 与 ABA 问题(完整整合版)
java·开发语言·jvm·安全·设计模式
会员果汁8 小时前
12.设计模式-状态模式
设计模式·状态模式
Yu_Lijing9 小时前
基于C++的《Head First设计模式》笔记——抽象工厂模式
c++·笔记·设计模式
会员果汁11 小时前
13.设计模式-适配器模式
设计模式·适配器模式
GISer_Jing1 天前
AI:多智能体协作与记忆管理
人工智能·设计模式·aigc
雨中飘荡的记忆1 天前
责任链模式实战应用:从理论到生产实践
设计模式
沛沛老爹1 天前
Web开发者进阶AI:Agent技能设计模式之迭代分析与上下文聚合实战
前端·人工智能·设计模式