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图

总结

  • 工厂方法模式相比简单工厂模式的优点?
    简单工厂模式在新增加功能时,需要修改工厂类,违背了开闭原则。工厂方法使一个类的实例化延迟到其子类,新增功能时增加一个工厂子类即可。缺点是由于每加一个产品,就需要加一个产品工厂的接口,增加了额外的开发量。
相关推荐
进击的小头1 小时前
设计模式组合应用:嵌入式通信协议栈
c语言·设计模式·策略模式
致Great1 小时前
智能体的设计模式探讨
设计模式
BD_Marathon3 小时前
设计模式——单一职责原则
设计模式·单一职责原则
stevenzqzq3 小时前
Slot API 设计模式
设计模式·compose
reddingtons3 小时前
Cascadeur:动态总是“飘”?“物理外挂流” 3分钟直出重力感 2D 立绘
游戏·设计模式·aigc·设计师·游戏策划·游戏美术·cascadeur
Wyy_9527*3 小时前
行为型设计模式——策略模式
设计模式·策略模式
kogorou0105-bit4 小时前
前端设计模式:发布订阅与依赖倒置的解耦之道
前端·设计模式·面试·状态模式
BD_Marathon4 小时前
设计模式——接口隔离原则
java·设计模式·接口隔离原则
小码过河.1 天前
设计模式——适配器模式
设计模式·适配器模式
钝挫力PROGRAMER1 天前
软件工程结构型设计模式
设计模式·软件工程