C语言设计模式:组合模式

The composite pattern describes thata group of objects are to be treated in the same way as a single instance of an object.The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.[1]

WIKI的解释很直观,组合模式强调的是一个对象和一组对象的无差别处理。


http://blog.csdn.net/feixiaoxing/article/details/7078836

上文这个家伙的举例也不错,C中常见的组合模式就是2级链表的遍历。

但原文代码不直观,尝试举例如下:系统有一个设备链,每个节点挂接同一类型的设备,这样就形成了2级链表。

如果需要对所有设备进行遍历,就需要用到该设计模式。


[cpp]  view plain
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
当然可以。以下是一个使用C语言编写的嵌入式硬件设计模式示例: ``` #include <stdio.h> // 建立一个抽象基类 typedef struct { void (*operation)(void); } Component; // 建立一个具体的类 typedef struct { Component component; char *name; } ConcreteComponent; void ConcreteComponent_operation(void) { printf("ConcreteComponent_operation\n"); } // 继承抽象基类并重写方法 typedef struct { Component component; Component *component_ptr; } Decorator; void Decorator_operation(void) { Decorator *decorator = (Decorator*)this; if (decorator->component_ptr != NULL) { decorator->component_ptr->operation(); } } // 建立一个具体的修饰器 typedef struct { Decorator decorator; char *name; } ConcreteDecorator; void ConcreteDecorator_operation(void) { ConcreteDecorator *concrete_decorator = (ConcreteDecorator*)this; printf("ConcreteDecorator_operation: %s\n", concrete_decorator->name); Decorator_operation(this); } int main() { // 创建具体对象 ConcreteComponent concrete_component = { .component = { .operation = ConcreteComponent_operation }, .name = "ConcreteComponent" }; printf("ConcreteComponent:\n"); concrete_component.component.operation(); // 创建修饰器对象 Decorator decorator = { .component = { .operation = Decorator_operation }, .component_ptr = NULL }; ConcreteDecorator concrete_decorator = { .decorator = decorator, .name = "ConcreteDecorator" }; concrete_decorator.decorator.component_ptr = &concrete_component.component; printf("ConcreteDecorator:\n"); concrete_decorator.decorator.component.operation(); return 0; } ``` 这个示例实现了装饰器模式,通过继承抽象基类 Component 和 Decorator 并重写方法来实现具体的类和修饰器。在 main 函数中创建了一个具体对象和一个修饰器对象,并将它们组合在一起。最终输出了它们的操作结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值