In a project that I\'ve been involved with for many years, I\'ve gradually evolved a design pattern that\'s proven to be extremely useful for me. I sometimes feel I should
Believe me or not. I was thinking the very same thing this morning.
I have used this pattern before but I've never found a reference for it nor know how to name it.
I think is a kind of "Keyed" singleton, where the instances are stored somewhere and they are obtained using a key.
The last time I use it was to retrieve data from different sources.
I had about 50 database tables ( make it 10 ) And I have a front end "table" where the data was to be displayed, but the data could come from any of those sources and each one require different logic ( queries, joins, keys, etc. )
This front end was "configurable" so I couldn't know what values were to be shown and which other won't.
The solution was to take the columnName ( in the front end ) as the key, and get the correct instance to create the right query.
This was installed in a hash map at the beginning and later retrieved from a database table.
The code was like this:
class DataFetcher {
abstract Object getData( Object id );
}
class CustomerNameDataFetcher extends DataFetcher {
Object getData( Object customerId ) {
// select name from customer where id = ?
}
}
class CompanyAdressDataFetcher extends DataFetcher {
Object getData( Object customerId ) { // don't ask why.
// select name from company , customer where customer.co = company.co and cu = ? etc.
}
}
class ProductColor extends DataFetcher {
Object getData( Object x ) {
// join from customer to color, to company to season to a bunch of table where id = ?
}
// And the list goes on.
Each subclass used different logic.
At runtime the user configured it's view, and select what he want to see.
When the user selected the columns to see, I used the column name and an Id to fetch the data.
The DataFetchers were all installed in the parent class ( I didn't want to have a separeate class for this ) in a class method.
class DataFetcher {
abstract Object getData( Object id );
private static final Map fetchers = new HashMap();static {
fetchers.put("customer.name", new CustomerNameDataFetcher() );
fetchers.put("company.address", new CompanyAdressDataFetcher () );
fetchers.put("product.color", new ProductColor () );
...
}
public static DataFetcher getFetcher( String id ) {
return fetchers.get( id );
}
}
At the end to fill the front end table I just call it like this:
pseudocode
for each row in table
for each column in row
column.text = DataFetcher.getFetcher( column.id ).getData( row.id )
end
end
Is it like this? Or do I misread your description and mine is quite different.
Finally I think this is called SingletonRegistry or something like that. I ( probably ) like you, created this out of necessity. Chances are this is a common pattern.