我開始一個新的應用程序,這將能夠在同一時間連接到很多不同的供應商數據庫。替代一個神級
在使用所有輕鬆的連接模式的思考,我做了這個代碼(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)和短代碼。與其他連接相同。 即使對我來說完美,大家都說這是反模式和所有。
我如何能實現幾乎相同的結果,如果沒有這個「助手」類,並且仍然能夠分享我的連接/設置各種形式的課程,沒有什麼傳遞給參數/構造。
謝謝。
你不需要任何您的通話新的。只需在堆棧上創建對象。例如。 '應用程序;'或'的std ::地圖<的UnicodeString,屋宇署> mpBdList;' – 2012-02-10 20:44:43