Factory Pattern
Factory Pattern
Types:
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 {
}
}
Step 4
Use the Factory to get object of concrete class by passing an information such as type.
FactoryPatternDemo.java
public class FactoryPatternDemo {
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.