gpt4 book ai didi

c++ - 神级的替代品

转载 作者:行者123 更新时间:2023-11-28 08:10:29 27 4
gpt4 key购买 nike

我正在启动一个新的应用程序,它将能够同时连接到不同提供商的大量数据库。

考虑到可以轻松使用所有连接的模式,我编写了这段代码 (C++):

class Bd
{
private:
TUniConnection* mpConnection;

public:
Bd::Bd()
{
mpConnection = new TUniConnection(NULL);
}

void Bd::setProvider(UnicodeString provider)
{
mpConnection->ProviderName = provider;
}

void Bd::connect()
{
mpConnection->Connect();
}

UnicodeString Bd::getProvider() const
{ return mpConnection->ProviderName; }

Bd::~Bd()
{ delete mpConnection; }
};

// In the right path to become a singleton-helper-utility-god-class
class App
{
public:
// Default bd. Just a shortcut.
Bd* bd;

App()
{ bd = getBd("BDMain"); }

~App()
{ delBd("BDMain"); }

Bd* getBd(UnicodeString key)
{
if(mpBdList[key] != NULL)
{
return mpBdList[key];
}
mpBdList[key] = new Bd;
return mpBdList[key];
}

void delBd(UnicodeString key)
{
delete mpBdList[key];
mpBdList[key] = NULL;
}

private:
std::map<UnicodeString, Bd *>mpBdList;
};

// Just an example of use.
int main()
{
// Consider this instance global/singleton/etc
App* app = new App;
app->bd->setProvider("Oracle");
app->connect();

// Outside the main, probably in some form (this method don't exist - yet)
app->bd->query("blah blah blah");

app->getBd("settings")->setProvider("SQLite");
app->getBd("settings")->connect();
app->getBd("settings")->query("blah blah blah");
}

显然还行不通,但你们可以了解我的想法。从理论上讲,看起来很完美。我可以轻松和简短的代码访问主连接 (app->bd)。与其他连接相同。即使对我来说是完美的,每个人都说那是反模式等等。

如果没有这个“助手”类,我如何才能获得几乎相同的结果,并且仍然能够将我的连接/设置共享给所有表单和类,而不向参数/构造函数传递任何内容。

谢谢。

最佳答案

我会让 mpBdList 成为 Bd 的静态私有(private)成员,同样地让 getBddelBd 静态方法Bd。那么你根本不需要 App 并且你仍然坚持一个概念,一个类的格言。我确信还有许多其他有效的设置方法。

关于c++ - 神级的替代品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9232801/

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