Factory Design Pattern in Java and Spring
Implementation of the Design Patterns in Java and Spring Framework
Factory Design Pattern is one the most popular Design Patterns and is just like a Singleton Design Pattern (that we discussed in the previous blog), creational Pattern. Factory Design Pattern takes the responsibility of creating different polymorphic objects through a centralized class. Need for such kind of behavior arises as a source code of a particular software system grows by quantity and complexity. As a result, the number of created objects rises and the system structure gets more chaotic.
The traditional way of implementing Factory Design Pattern is to gather the creation of sibling objects in one Factory class and let that class only decide in which situation, which object should be created.
In the following example, we have got a CashFlowService interface with one save() abstract method that will be implemented by IncomeServiceImpl and ExpenseServiceImpl classes. Based on a situation CashFlowFactory class will decide which implementation to use.

Often Factory and Singleton design Patterns are used together in order to have a full control over object instantiation. Here you can take a look at a similar example in my git account.
Without exaggerating we can confidently state that, the Factory Design Pattern is the fundamental part of the Spring Framework.
The bean initialization in Spring is based on Factory Design Pattern. The BeanFactory (org.springframework.beans.factory.BeanFactory) interface with bunch of abstract methods allow us to initialize different beans providing fundament for Dependency Injection. Basically each getBean() method is an implementation of Factory Design Pattern. Although BeanFactory is basics for bean initialization, more modern ,method is using ApplicationContext. On the other hand, BeanFactory supports only xml-based configuration. Since xml-based configuration is a bit outdated, we will take a look at more modern approaches.
ApplicationContext (org.springframework.context.ApplicationContext) which is extension of BeanFactory, adds extra functionality to the application to be configurable with different contexts. With this superset we can also implement java-based and annotation-based configuration. In java-based configuration, we use, basically @Bean annotation to indicate that we are creating objects, whereas in annotation-based configuration we are relying on different context based annotations for bean creation (such as @Component, @Controller, @Service, @Repository, @Autowired ).






