PDA

View Full Version : two implementation of one interface


zhoullhh
05-11-2007, 04:04 AM
I have two implementation classes, AI, BI for one interface: I. I would like to get one of them based on my configuration. The configuration is user configurable. how would I do that? I am trying to look for the best way.

I think that I can do the following:
1. config one instance for one class AI, BI in the spring configuration file, and then in the code, using Spring to GetObject("") method to get anyone of them. By this way, I have to use Spring act as a service locator.

2. Create a Factory class, and point my other classes who is using AI or BI to use the Factory, instead of AI, BI directly. But by this way, I am using my AI, BI type directly in the code, which is not what I want to do and not the style of using Spring, I think.


Another question is about the user configuration. If my object is depends on the configruation and it's dynamically configurable by the users, what is the best way. Right now, I clear the context and have it reload, and reset all of object to new configuration, dynamically regenerate new objects based on the new configuration.

Any better thoughts? thanks.


thanks.

Erich Eichinger
05-11-2007, 07:21 AM
Hi,

You could implement the interface IFactoryObject, who's GetObject() method decides, which instance to hand out:


class MyAorBFactory : IFactoryObject
{
...
public object GetObject()
{
if (conditionForA) return new A(); else return new B();
}
}


and configure your object as


<object id="MyAorBImplementation" type="MyAorBFactory" />



cheers,
Erich

zhoullhh
05-11-2007, 04:37 PM
Erich, thanks for reply.

Well, this approach is still not that great. It can save me to write one interface to get that object, however, it makes the factory depends on the Spring framework.