3.设计模式-装饰模式

定义:动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。

需求

要求写一个可以给人搭配不同的服饰的系统,比如类似QQ、网络游戏或论坛都有的Avatar系统。

需求分析

  • 针对一个对象会动态新增代码
  • 增加的顺序不固定

代码

被装饰类

c 复制代码
typedef struct Person {
    char *name;
    void (*show)(struct Person *);
} Person;
void PersonShow(Person *mthis) {
    printf("装扮的%s\n", mthis->name);
}
Person *ConstructPerson(char *name) {
    Person *obj = (Person *)malloc(sizeof(Person));
    obj->name = name;
    obj->show = PersonShow;
    return obj;
}

装饰类

c 复制代码
typedef struct Decorator {
    Person base;
    Person *decorated;
} Decorator;
void DecoratorShow(Person *mthis) {
    printf("%s ", mthis->name);
    ((Decorator *)mthis)->decorated->show(((Decorator *)mthis)->decorated);
    return;
}
Decorator *ConstructDecorator(char *decoratorName, Person *p) {
    Decorator *obj = (Decorator *)malloc(sizeof(Decorator));
    obj->base.name = decoratorName;
    obj->decorated = p;
    obj->base.show = DecoratorShow;
    return obj;
}

客户端使用

c 复制代码
int main() {
    Person *p = ConstructPerson("小菜");
    Decorator *pqx = ConstructDecorator("破球鞋", p);
    Decorator *kk = ConstructDecorator("垮裤", (Person *)pqx);
    Decorator *dtx = ConstructDecorator("大T恤", (Person *)kk);
    dtx->base.show((Person *)dtx);
    return 0;
}

当前代码是在person类前装饰,想改变装饰方式,在代码前后都做操作怎么弄?

新建一个类继承decorate, 重新实现一show方法和"构造函数"。------符合开闭原则

对C语言实现类之间关系的新认识

  • 如何继承
  • 如何聚合
c 复制代码
typedef struct Decorator {
    Person base;	// Decorator类继承Person
    Person *decorated; // Decorator类由Person类聚合
} Decorator;

UML图

"构造函数"和函数调用时的本对象没画

总结

  • 装饰模式封装了什么变化?
    封装了为已有功能动态地添加更多功能,添加方式的变化。每一个变化也只需关注自身实现功能。
  • 重构代码或功能开发时如何使用装饰模式?
    把类中的装饰功能从类中搬移去除,这样可以简化原有的类。把类的核心职责和装饰功能区分开了。而且可以去除相关类中重复的装饰逻辑。
相关推荐
_哆啦A梦15 小时前
Vibe Coding 全栈专业名词清单|设计模式·基础篇(创建型+结构型核心名词)
前端·设计模式·vibecoding
阿闽ooo4 天前
中介者模式打造多人聊天室系统
c++·设计模式·中介者模式
小米4964 天前
js设计模式 --- 工厂模式
设计模式
逆境不可逃4 天前
【从零入门23种设计模式08】结构型之组合模式(含电商业务场景)
线性代数·算法·设计模式·职场和发展·矩阵·组合模式
驴儿响叮当20104 天前
设计模式之状态模式
设计模式·状态模式
电子科技圈4 天前
XMOS推动智能音频等媒体处理技术从嵌入式系统转向全新边缘计算
人工智能·mcu·物联网·设计模式·音视频·边缘计算·iot
徐先生 @_@|||4 天前
安装依赖三方exe/msi的软件设计模式
设计模式
希望_睿智5 天前
实战设计模式之访问者模式
c++·设计模式·架构
茶本无香5 天前
设计模式之十六:状态模式(State Pattern)详解 -优雅地管理对象状态,告别繁琐的条件判断
java·设计模式·状态模式
驴儿响叮当20105 天前
设计模式之备忘录模式
设计模式·备忘录模式