使用 ANSI C 实现工厂模式
谁能给我指点一下如何使用 ANSI C 实现工厂模式的参考资料?如果涵盖更多模式,那将是一个额外的好处。在 C++ 中执行此操作对我来说微不足道,但由于 C 没有类和多态性,我不太确定如何执行此操作。我正在考虑拥有一个包含所有常见数据类型的“基本”结构,然后使用 void 指针,并按照与顶部基本结构中相同的顺序定义结构的所有公共部分?或者不能保证它们在记忆中以相同的方式结束?
Can anyone point me to a reference on how to implement the factory pattern using ANSI C? If more patterns are covered to that would just be a bonus. Doing this in C++ i trivial for me, but since C does not have classes and polymorphism I'm not quite sure how to do it. I was thinking about having a "base" struct with all the common data types and then using void pointers, and defining all the common parts of the structs in the same order as in the base struct at the top? Or is it not guaranteed that they end up in the same way in memory?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
工厂模式也可以在 C 中实现,假设以下是您的接口定义的操作:
因此,为了能够获得实现此类接口的实现实例,
您应该定义一个包含数据和操作的结构,然后您可以定义创建
将返回该结构的操作,也可能是销毁操作:
您还应该定义一个为您提供工厂方法的函数,
也许你应该有一种方法来获得正确的实施
您的需求(可能不是像下面的示例中那样的简单参数):
所以它将像这样使用:
Factory pattern can be implemented in C also, suppose the following are the operations that your interface defines:
So, to be able to get an implementations instance that implements such interface,
you should define a structure with both data and operations, then you can define the create
operation that will return to you that structure and probably a destroy operations also:
You should also define a function that provides you the factory methods,
maybe you should have a way to get the right implementation basing on
your needs (probably not a simple parameter like in the example below):
So it will be used like:
C 有函数指针和结构体。所以你可以用 C 实现类。
这样的东西应该会给你一个线索。
C have function pointers and structs. So you can implement classes in C.
something like this should give you a clue.
这里位于页面底部,是一系列有关 C 语言模式的文章
Here, at the bottom of the page, is a series of articles about patterns in C
工厂模式是一种面向对象的设计模式。
C 不是面向对象的语言。
因此,我会质疑你在 C 语言中建立工厂的目标是什么。
The Factory pattern is an Object-Oriented design pattern.
C is not an Object-Oriented language.
Therefore, I would question what your goal is for a Factory in C.