Spring – Factory Pattern | Code Factory


Donate : Link

Medium Blog : Link

Applications : Link

This image has an empty alt attribute; its file name is image-1.png

Spring Tutorial Index Page: 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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s