You are on page 1of 4

Factory Pattern

 One of the most popular design patterns in Java


 Design patterns: well described solution for solving specific task or problem.
 Advantages: 1- Reusable in multiple project.
2- Define system structure.
3- Clarity to the system architecture.
4- Transparency to the design in the application.
5- Well proved and testified solution.
6- Spend less time to solve a problem.
7- Factory Method is that it can return the same instance multiple
times, or can return a subclass rather than an object of that exact type.
 Disadvantages:
1- Indirection may reduce performance.
2- Limitation (may not be addressed specific issues).

 Types:

 Comes under creational pattern.


 Objectif: Creates an object by calling a method instead of a constructor.
 Demo :
Step 1
Create an interface.
Operator.java
public interface Operator {
void pay();
}

Step 2
Create concrete classes implementing the same interface.
Mtn.java
public class Mtn implements Operator {

@Override
public void pay() {
System.out.println("Inside Mtn::pay() method.");
}
}
Vodaphone.java
public class Vodaphone implements Operator {

@Override
public void pay() {
System.out.println("Inside Vodaphone::pay() method.");
}
}
Orange.java
public class Orange implements Operator {

@Override
public void pay() {
System.out.println("Inside Orange::pay() method.");
}
}

Step 3
Create a Factory to generate object of concrete class based on given information.
ShapeFactory.java
public class OperatorFactory {

//use getOperator method to get object of type operator


public Operator getOperator(String OperatorType){
switch (OperatorType)
{
case "MTN":
return new Mtn();
case "Vodaphone":
return new Vodaphone();
case "Orange":
return new Orange();
case:
throw new NotSupportedException ();
}

}
}

Step 4
Use the Factory to get object of concrete class by passing an information such as type.
FactoryPatternDemo.java
public class FactoryPatternDemo {

public static void main(String[] args) {


OperatorFactory opFactory = new OperatorFactory ();

//get an object of Mtn and call its pay method.


Operator op = opFactory.getOperatoe("MTN");

//call pay method of Mtn


op.pay();

//get an object of Vodaphone and call its pay method.


Operator op2 = opFactory.getOperatoe("Vodaphone");
Op2.pay();
}
}

 Best Practice:
 Use the Factory Method when you don’t know beforehand the exact types and
dependencies of the objects : to add a new product type to the app, we’ll only need
to create a new creator subclass and override the factory method in it.
 Use the Factory Method when you want to save system resources by reusing existing
objects instead of rebuilding them each time.

You might also like