Intent:
It defines an interface for the creation of objects and hide the creational logic from the client. It enables the user to use the newly created object without knowing their creational details.
Also, knows as virtual constructor.
Applicability:
Use the factory method when;
- a subclass wants to specify which type of object they want.
- you want to keep all the creation object in one place.
Implementation:
abstract class Computer{
void spec();
}
class Corei5 implements Computer{
void spec(){
print("Core i5 with 8gb Ram");
}
}
class Corei7 implements Computer{
void spec(){
print("Core i7 with 16gb Ram");
}
}
class ComputerFactory {
Computer getComputer(String name){
if(name=='corei5'){
return Corei5();
}else{
return Corei7();
}
}
}
void spec();
}
class Corei5 implements Computer{
void spec(){
print("Core i5 with 8gb Ram");
}
}
class Corei7 implements Computer{
void spec(){
print("Core i7 with 16gb Ram");
}
}
class ComputerFactory {
Computer getComputer(String name){
if(name=='corei5'){
return Corei5();
}else{
return Corei7();
}
}
}
void main() {
ComputerFactory factory=ComputerFactory();
Computer computer=factory.getComputer("corei5");
computer.spec();
}
For more details see this tutorials;
1. https://www.tutorialspoint.com/design_pattern/factory_pattern.htm
2. https://github.com/iluwatar/java-design-patterns/tree/master/factory