为以命令式风格编写的 C 程序实现 OO 接口的模式

Pattern to Implement an OO interface to a C program written in an imperative style

想象一个以命令式风格编写的遗留 C 程序:自上而下,没有对象,并带有 goto 语句。这个程序在观察者模式中实现了一个依赖;即,发布-订阅架构中的订阅者。

任务是为所述程序实现 OO 接口。

哪种设计模式最适合这里?一开始,我跳到一个 Adapter 模式:

适配器

Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces [Go4, 8]

这里的问题是一个适配器转换了另一个class的接口。在这种情况下,没有 class 可以转换; C 没有 classes.

接下来我想proxy:

代理服务器

Provide a surrogate or placeholder for another object to control access to it. [Go4, 9]

这符合——有点——但似乎没有抓住我正在尝试做的事情的本质。

门面

Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-elevel interface that makes the subsystem easier to use. [Go4, 9]

也许...这可能是最好的选择,但我不确定。

哪种设计模式最适合这种场景?谢谢,基思 :^)

模式使您可以更轻松地向已经熟悉相同模式的其他人解释您在做什么;它们不会自动让您的工作更轻松。

在您的情况下,似乎根本不需要任何模式:您正在编写 C++ classes 来定义发布-订阅系统的接口,并在成员函数内调用 C 函数实现接口。这是基本的封装:您的 C++ classes 的用户不知道实现内部发生了什么,而实现对他们隐藏了所有 spaghetti/gotos。

您可以将其描述为适配器模式的应用,即使您拥有的只是 C 函数的集合,而不是 classes。在非常一般的层面上,非 OO 函数可以被认为是单个顶层 class 的 class 函数;您的 "adapter" 将一组 classes 作为 C++ 接口放在它们之上。