Spring — Factory Pattern | Code Factory

Donate : Link

WordPress Blog : Link

Applications… : Link

  • What is factory and use of factory?
  • We use to create object of other classes.
  • * Factory classes main aim is to they will make clients independent by returning object in the form of Interface reference.
  • * Example: DriverManager is a factory class. Connection is an interface. DriverManager.getConnection() method will return object of Connection irrespective of database. Same code is use for any database so it will making us database independent.
  • By factory we will hide object creation logic.
  • * Logger is a static factory and SessionFactory is a instance factory.
  • Some points of factory
    - Hide instantiation logic
    - By returning instance into Interface reference Factory will make clients independent irrespective of implementation
  • Many databases given implementation for Connection interface.
interface Car {
public void drive();
}
class CarFactory {
private CarFactory() {
}
public static Car getCar(String carName) {
return (Car) Class.forName(carName).newInstance();
}
}
class JLR implements Car {
public void drive() {
sop("Maximum speed is 250");
}
}
class Audi implements Car {
public void drive() {
sop("Maximum speed is 200");
}
}
class Test {
psvm(String args[]) {
Car c = CarFactory.getCar("JLR");
}
}
  • To implement factories in Spring we have 3 approaches.
  1. Spring — Static Factories
  2. Spring — Instance Factories
  3. Spring — FactoryBean

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store