Reputation: 135
Is it a good practice to have objects specific to some implementation as member variables in a factory class ? For e.g., in the code below, s1 and s2 are required for constructing OneChannel and secondChannel objects respectively. Is it a good practice to declare these as member variables inside the factory ? If not, what can e the other alternative.
public class CommunicationChannelFactoryImpl {
@Autowired
SomeClass s1;
@Autowired
SomeOtherClass s2;
public CommunicationChannel getCommunicationChannel(String channel, Map<String, String> channelProperties) {
if(channel.equals("ONE") {
return new OneChannel(s1);
}
if(channel.equals("TWO") {
return new SecondChannel(s2);
}
}
}
Please note that s1 ad s2 are singleton beans
Upvotes: 1
Views: 93
Reputation: 18423
Why don't let Spring create OneChannel() and SecondChannel() object using BeanFactoryAware
?
public class CommunicationChannelFactoryImpl implements BeanFactoryAware {
FactoryBean factoryBean;
public void setBeanFactory(FactoryBean factoryBean) {
this.factoryBean = factoryBean;
}
public CommunicationChannel getCommunicationChannel(String channel, Map<String, String> channelProperties) {
if(channel.equals("ONE") {
return this.factoryBean.getBean("oneChannel");
}
if(channel.equals("TWO") {
return this.factoryBean.getBean("secondChannel");
}
}
}
and define your XML (or JavaConfig, but I'm not using it) as:
<bean id="oneChannel" scope="prototype">
<constructor-arg index="0" ref="s1" />
</bean>
<bean id="secondChannel" scope="prototype">
<constructor-arg index="0" ref="s2" />
</bean>
<bean id="s1" class="path.to.SomeClass" />
<bean id="s2" class="path.to.SomeOtherClass" />
Upvotes: 0
Reputation: 29186
Since you need those beans for constructing those particular channel implementations, I think you can keep them as properties in that particular factory implementation. You are injecting the required components, so you have the flexibility to change the implementations later if you need.
Also, it will be better if SomeClass
and SomeOtherClass
are some abstractions/interfaces/super type. In this way if you ever need to provide different implementations for building those channel objects in the future, you'll be able to do so pretty easily.
Upvotes: 1