I’m starting a new app, that will be able to connect to a lot of databases of different providers at the same time.
Thinking in a pattern to use all the connections with ease, i made this code (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");
}
Obviously doesn’t work yet, but you guys can have a clue of my thought.
Theorically, looks perfect.
I can access the main connection (app->bd) with ease and short code. The same with other connections.
Even perfect to me, everybody is saying that is anti-pattern and all.
How can i achieve the almost same result, without this “helper” class, and still able to share my connections/settings to all forms and classes, without passing nothing to parameters/constructors.
thanks.
I would make
mpBdLista static private member ofBd, and similarly makegetBd,delBdstatic methods ofBd. Then you don’t needAppat all and you’re still adhering to the one concept, one class dictum. I’m sure there are many other valid ways to set up things as well.