是否有任何“设计模式”?在C语言中?
我知道设计模式通常与 OO 编程相关,但是您在进行 C 编程时是否有一些经常使用的模式?
我对经典面向对象模式的简单翻译不感兴趣,请不要提及 Duff 的设备。 ;-)
I know that design patterns is generally something that's connected to OO programming, but do you have some pattern you often use when you program C?
I'm not interested in simple translations of the classical OO patterns and please don't mention Duff's device. ;-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我最喜欢的是 Adam Tornhill 的“C 模式”系列:
另外:我总是想到
goto
作为装饰器模式的一个伟大的穷人工具。更新:我强烈建议使用Rust (rust-lang.org) 或 Zig (ziglang.org) 而不是 C,除非您需要使用 c。 Rust 具有 c 的所有优点,包括速度和与 c 的二进制库兼容性,但编译器处理大部分复杂性以确保代码内存安全并且不包含数据竞争。它也是可移植的,具有用于常见任务的标准库,并且更容易针对各种设计模式进行编程。
My favorite is the "Patterns in C" series by Adam Tornhill:
Also: I always think of
goto
as a great poor man's tool for the decorator pattern.Update: I'd highly recommend using Rust (rust-lang.org) or Zig (ziglang.org) rather than C except where you are required to use c. Rust has all of the benefits of c, including speed and binary library compatibility with c, but the compiler handles much of the complexity to ensure that the code is memory safe and does not contain data races. It's also portable, has a standard library for common tasks, and much easier to program with for various design patterns.
设计模式可以被视为缺失的语言功能。 设计模式:可重用面向对象软件的元素中指出:
斜体的句子是你问题的答案。
Design Patterns could be viewed as missing language features. The Introduction of Design Patterns: Elements of Reusable Object-Oriented Software states:
The sentence in italics is the answer to your question.
通过回调实现多态性,例如标准库的
qsort
函数。它所需要的只是一种比较两个元素的方法,并且它可以对它们的数组进行排序。通过使用函数集(vtable)来表示类型的相关属性,以便通用例程可以有效地处理它,您可以比这更复杂。例如,读取、写入等调用打开的文件或网络端口。
Polymorphism via callbacks, e.g. the standard library's
qsort
function. All it needs is a way to compare two elements, and it can sort an array of them.You can be much more sophisticated than this by using sets of functions (vtables) to represent the pertinent properties of a type so that a generic routine can process it usefully. For example, the read, write, etc. calls on an open file, or network port.
从我的头顶开始
From the top of my head
是的,有。延迟初始化、单例、对象池、对象状态等很容易用纯C实现。
示例(延迟初始化)
Yes, there are. Lazy initialization, singleton, object pool, object state etc. are easily implemented in pure C.
Example (lazy initialization)
设计模式通常对现有环境提供的事物仅进行一级建模。如果您将 C 及其标准库作为环境,那么一个著名的设计模式就是面向对象。
Design Patterns often model things that are just one level from what an existing environment offers. If you take C with its standard library as the environment an eminent design pattern is Object Orientation.
虚拟文件系统是学习设计模式的完美示例。
Virtual File System is perfect example for learning the Design Pattern.