gpt4 book ai didi

c++ - 在单个接口(interface)后面隐藏多个实现

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:15:03 25 4
gpt4 key购买 nike

我知道 Strategy 和 Abstract Factory 设计模式 - 但是它们不能解决我当前的问题:

我正在创建一个提供非常基本的 GUI 的 C++ 库。但是我希望用户能够在编译时选择使用哪个 GUI 库(比如 Qt 或 FLTK)来实际呈现 GUI。然而,用户应该只需要了解我的库中的方法。

使用 Qt 后端或 FLTK 后端应该可以在不进行任何更改的情况下编译相同的代码。

我想到了这样的事情:

class A
{
// do things that are not specific to QT or FLTK here as there are many
// methods I will need independent of the backend
}

class QT_A : public A
{
// Implement the actual creation of a window, display of a widget here using Qt
}

class FLTK_A : public A
{
// Implement the actual creation of a window, display of a widget here using FLTK
}

问题是我不想让用户知道QT_AFLTK_A。用户(开发人员)应该只处理A。另外,我不能同时拥有这两种变体,因为我不希望我的库同时依赖于 Qt 和 FLTK;只是在编译时选择的那个。

最佳答案

一个选项是另一个答案中描述的 Pimpl 习语。

另一个选项是工厂返回一个指向接口(interface)类的指针:

std::unique_ptr<A> make_A()
{
#if defined(USING_QT)
return std::unique_ptr<A>(new QT_A(...));
#elif defined(USING_FLTK)
return std::unique_ptr<A>(new FLTK_A(...));
#else
#error "No GUI library chosen"
#endif
}

关于c++ - 在单个接口(interface)后面隐藏多个实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14486080/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com