设计模式
工厂模式生成bean
工厂模式分为静态工厂和实例工厂
静态工厂:
#静态工厂通过静态方法获取实例,实例为静态方法和类初始化一起
<bean id="clientService"
class="examples.ClientService"
factory-method="createInstance"/>
public class ClientService {
private static ClientService clientService = new ClientService();
private ClientService() {}
// 静态方法
public static ClientService createInstance() {
return clientService;
}
}
实例工厂
# 实例工厂有专门的工厂类,根据不同工厂方法获取不同的实例类型
# DefaultServiceLocator 为实例工厂类
<bean id="serviceLocator" class="examples.DefaultServiceLocator">
<!-- inject any dependencies required by this locator bean -->
</bean>
<bean id="clientService"
factory-bean="serviceLocator"
factory-method="createClientServiceInstance"/>
<bean id="accountService"
factory-bean="serviceLocator"
factory-method="createAccountServiceInstance"/>
public class DefaultServiceLocator {
private static ClientService clientService = new ClientServiceImpl();
private static AccountService accountService = new AccountServiceImpl();
public ClientService createClientServiceInstance() {
return clientService;
}
public AccountService createAccountServiceInstance() {
return accountService;
}
}