When to use Factory Design Pattern :
The Factory Method pattern is generally used in the following situations:
- A class cannot anticipate the type of objects it needs to create beforehand.
- A class requires its subclasses to specify the objects it creates.
- You want to localize the logic to instantiate a complex object.
- Belongs to creational design patterns
- Low coupling and more cohesion
public interface OS { void printOsName(); }
public class Linux implements OS{ @Override public void printOsName() { System.out.println("This is linux operating system"); } }
public class IOS implements OS{ @Override public void printOsName() { System.out.println("This is IOS operating system"); } }
public class Windows implements OS{ @Override public void printOsName() { System.out.println("This is windows operating system"); } }
public class OSFactory { public OS getOsInstance(String input) { if(input.equalsIgnoreCase("Secure")) { return new IOS(); }else if(input.equalsIgnoreCase("MostUsed")) { return new Windows(); }else { return new Linux(); } } }
public class FactorDesignPatternDemo { public static void main(String[] args) { OS obj; obj = new OSFactory().getOsInstance("MostUsed"); obj.printOsName(); obj = new OSFactory().getOsInstance("Secure"); obj.printOsName(); obj = new OSFactory().getOsInstance("Others"); obj.printOsName(); } }
Read Me : (Reference)
https://medium.com/@kousiknath/design-patterns-different-approaches-to-use-factory-pattern-to-choose-objects-dynamically-at-run-71449bceecef #java 8 https://medium.com/@mhd.durrah/factory-pattern-the-dynamic-way-with-java-8-3ca5ab48a9cf