Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
- In Factory Pattern we have Product(Abstract), ConcreteProduct and Creator(Abstract), ConcreteCreator
- ConcreteCreator would create ConcreteProduct by implementing abstract factory method of Creator which has Product return type
- Incase if there is any new Product to be added it fully supports Open Closed Principle(Open For Extension, Closed for Changes).
- Open for Extension – Adding new ConcreteProduct and ConcreateCreator class, Closed for Changes – No changes in anyother code unlike Simple factory or static factory method which requires change in Switchcase, enum (or) if case
- Closed for Changes – No changes in anyother code unlike Simple factory or static factory method which requires change in Switchcase, enum (or) if case
JobProfile.java
abstract class JobProfile { public abstract String mandatorySkills(); public Integer defaultWorkHrs(){ return 8; } }
JavaProfile.java
public class JavaProfile extends JobProfile{ @Override public String mandatorySkills() { return "Java, Springboot, Microservices"; } }
SQLProfile.java
public class SQLProfile extends JobProfile{ @Override public String mandatorySkills() { return "Cosmos, MySQL, MSSQL"; } }
JobProfileCreator.java
abstract class JobProfileCreator { public JobProfile getJobProfile(){ JobProfile objJobProfile = createJobProfileFactory(); return objJobProfile; } public abstract JobProfile createJobProfileFactory(); }
JavaProfileCreator.java
public class JavaProfileCreator extends JobProfileCreator { @Override public JobProfile createJobProfileFactory() { return new JavaProfile(); } }
SQLProfileCreator.java
public class SQLProfileCreator extends JobProfileCreator { @Override public JobProfile createJobProfileFactory() { return new SQLProfile(); } }
Consultancy.java
public class Consultancy { public static void main(String[] args) { getProfileDetails(new JavaProfileCreator()); } public static void getProfileDetails(JobProfileCreator jobProfileCreator){ JobProfile objJobProfile = jobProfileCreator.getJobProfile(); System.out.println(objJobProfile.mandatorySkills() + " with "+ objJobProfile.defaultWorkHrs() + "hrs of Work"); } }
Output
Java, Springboot, Microservices with 8hrs of Work