Okay it doesn’t have to be 8 environments or 3 databases. :P
And pardon me for using the term Database to refer to DBMS. (What it really should be called … read the book Relational Theory by CJ Date) :P
In a typical scenario, you have multiple environments, for example, SIT, UAT, Pre-production, production and disaster recovery.
On top of that, you have have multiple databases in each environment, for example, Edwards Payroll database, Resource Planning database and Customer Relation Management database.
Rarely will you need to build an application that connects to so many environments and databases. But when you do need this, you can use the Decorator pattern to implement the requirement.
Why Inheritance Doesn’t Help
If you knew inheritance, this would have been an good situation to put into practice some OO concepts, however as you will soon see, using inheritance-only gives rise to class explosion as the number of classes increase with the number of environments and databases that you want to connect to.
SIT, UAT, PPT and Production.
ERP, Payroll, CRM, and Billing.
As you see from the above, it is simply not feasible to maintain this complexity if using inheritance-only.
The Decorator Pattern
The Java I/O package is based on Decorator design pattern, at least from 1.0 through 6 (Technical name 1.6), including 1.4.2.
How you commonly construct IO objects is what the decorator is about, and you were probably wondering why the weird idiom.
BufferedReader stdin = new BufferedReader(new InputStreamReader(new InputStream());
(I am sorry my code format plugin is not working at writing, when i get it back (if i do … or if somebody can drop me a mail to help ><), i will change the font family for readability.)
This is how our implementation looks like.
To get a SIT environment Payroll connection:
(new Payroll(new SITEnvironment())).getSession()
To get a Production environment CRM connection:
(new CRM(new ProductionEnvironment())).getSession()
The chapter on Decorator pattern is available for download freely from OReilly.