The category “Animal” is an interface. All of those have four legs so it will try to return the animals with four legs. The “Domestic Animal” factory would manage these classes.
For example, if a customer goes to a “Domestic Animal” factory and he requests animals with four legs and weight of 25kg. The factory would return the dog object as it will be more appropriate than the cat.
The outside world is uncertain if it is a wild animal or domestic animal factory. If the requirements for this “Animal Factory” is that “I need a wild animal. The legs of that animal should be four, and the weight should be less than 4kg.”
These are the three requirements based on which the “Animal Factory” would try to return the appropriate factory. Here, the appropriate factory would be “Wild animal” factory. And it will try to return the appropriate object for the criteria which would be a “lion”.
public interface Course { public String getCourseName(); }
public class ProgrammingCourse implements Course { @Override public String getCourseName() { return "Java"; } }
public class NonProgrammingCourse implements Course { @Override public String getCourseName() { return "DSP"; } }
public interface Source { public String getSourceName(); }
public class Offline implements Source { @Override public String getSourceName() { return "Books"; } }
public class Online implements Source { @Override public String getSourceName() { return "YouTube"; } }
public abstract class SourceCourseFactory { public abstract Source getSource(String sourceType); public abstract Course getCourse(String courseType); }
public class CourseFactory extends SourceCourseFactory { @Override public Source getSource(String sourceType) { return null; } @Override public Course getCourse(String courseType) { if(courseType.equalsIgnoreCase("programming")) { return new ProgrammingCourse(); } else if(courseType.equalsIgnoreCase("non programming")) { return new NonProgrammingCourse(); } else { return null; } }
<br />public class SourceFactory extends SourceCourseFactory<br />{</p><p>@Override<br />public Source getSource(String sourceType)<br />{<br />if(sourceType.equalsIgnoreCase("online"))<br />{<br />return new Online();<br />}<br />else if(sourceType.equalsIgnoreCase("offline"))<br />{<br />return new Offline();<br />}<br />else<br />{<br />return null;<br />}<br />}</p><p>@Override<br />public Course getCourse(String courseType)<br />{<br />return null;<br />}</p><p>}<br />
public class ExampleMain { public static void main(String[] args) { SourceCourseFactory course = FactoryCreator.getSourceCourseFactory("course"); System.out.println(course.getCourse("programming").getCourseName()); SourceCourseFactory source = FactoryCreator.getSourceCourseFactory("source"); System.out.println(source.getSource("online").getSourceName()); } }