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图

总结

  • 工厂方法模式相比简单工厂模式的优点?
    简单工厂模式在新增加功能时,需要修改工厂类,违背了开闭原则。工厂方法使一个类的实例化延迟到其子类,新增功能时增加一个工厂子类即可。缺点是由于每加一个产品,就需要加一个产品工厂的接口,增加了额外的开发量。
相关推荐
szm022510 小时前
设计模式-
设计模式
砍光二叉树10 小时前
【设计模式】创建型-抽象工厂模式
设计模式·抽象工厂模式
砍光二叉树11 小时前
【设计模式】创建型-工厂方法模式
设计模式·工厂方法模式
我爱学习_zwj12 小时前
设计模式-2(单例模式与原型模式)
前端·javascript·设计模式
砍光二叉树12 小时前
【设计模式】创建型-单例模式
单例模式·设计模式
我爱学习_zwj12 小时前
设计模式-3(装饰器模式)
前端·设计模式·装饰器模式
文心快码BaiduComate1 天前
Comate内置模型已支持 MiniMax-M2.7!
设计模式·程序员·前端框架
console.log('npc')1 天前
Cursor,Trae,Claude Code如何协作生产出一套前后台app?
前端·人工智能·react.js·设计模式·ai·langchain·ai编程
czxyvX1 天前
C++ - 基于多设计模式下的同步&异步日志系统
c++·设计模式
蒸蒸yyyyzwd1 天前
设计模式之美学习笔记
笔记·学习·设计模式