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图

总结

  • 工厂方法模式相比简单工厂模式的优点?
    简单工厂模式在新增加功能时,需要修改工厂类,违背了开闭原则。工厂方法使一个类的实例化延迟到其子类,新增功能时增加一个工厂子类即可。缺点是由于每加一个产品,就需要加一个产品工厂的接口,增加了额外的开发量。
相关推荐
@zulnger2 小时前
python 设计模式
设计模式
Poetinthedusk18 小时前
设计模式-命令模式
windows·设计模式·c#·wpf·命令模式
雨中飘荡的记忆18 小时前
设计模式之桥接模式:从原理到实战
设计模式
北海屿鹿19 小时前
设计模式概述
设计模式
真夜21 小时前
发布观察者模式使用场景记录
设计模式
会员果汁1 天前
4.设计模式-代理模式
设计模式·代理模式
有一个好名字1 天前
设计模式-代理模式
java·设计模式·代理模式
catchadmin1 天前
PHP 之高级面向对象编程 深入理解设计模式、原则与性能优化
设计模式·性能优化·php
郝学胜-神的一滴1 天前
使用EBO绘制图形:解锁高效渲染与内存节省之道
c++·qt·游戏·设计模式·系统架构·图形渲染