隐藏单个接口后面的多个实现 [英] Hiding multiple implementations behind a single interface

查看:163
本文介绍了隐藏单个接口后面的多个实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道策略和抽象工厂设计模式 - 但是它们不能解决我当前的问题:

I know about the Strategy and Abstract Factory design patterns - however they don't solve my current problem:

我创建了一个C ++库,基本GUI。但是我希望用户能够在编译时选择使用哪个GUI库(例如Qt或FLTK)来实际渲染GUI。用户应该只需要知道我的库中的方法。

I'm creating a C++ library that offers a very basic GUI. However I want the user to be able to choose at compile time which GUI library to use (say Qt or FLTK) to actually render the GUI. The user should however only need to know about the methods in my library.

应该可以使用Qt后端或FLTK编译相同的代码,而不需要任何更改

It should be possible to compile the same code without any changes using either a Qt backend or an FLTK backend.

我想到了类似的东西:

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_A FLTK_A 。用户(开发人员)应该只处理 A 。此外,我不能同时有两个变种,因为我不想让我的库依赖于Qt和FLTK;

The problem is that I do not want the user to know about QT_A or FLTK_A. The user (developer) should just deal with A. Also, I can't have both variants at the same time as I don't want my library to depend on both Qt and FLTK; just whichever was chosen at compile time.

推荐答案

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

One option is the Pimpl idiom described in another answer.

另一种选择是返回指向接口类的指针的工厂:

Another option is a factory returning a pointer to the interface class:

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
}

这篇关于隐藏单个接口后面的多个实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆