The factory design pattern is used to hide the implementation logic of the factory object, and its power is to use inheritance to achieve this. Say you would have more than one type of person, for example. SmartPerson and DumbPerson (implementing the same base class Person). One could ask the factory to create a smart or dumb person, not knowing the differences in implementation, since everything he ever returns is a Person object.
You can create an instance of a person with a function that references the constructor, but this template refers to the location of the creation of the object, which allows you to hide certain implementation logic.
This hiding the logic behind the factory will save you a lot of time in the future, when different classes can use the factory to create people, since changing the way people are created will only require changing the creation methods in the factory and do not affect each individual class using the factory.
@Test public void testSimpleFactory() { PersonFactory personFactory = new PersonFactory(); Person person = personFactory.createPerson("dumb"); person.doMath(); // prints 1 + 1 = 3 } public class PersonFactory { public Person createPerson(String characteristic) { switch (characteristic) { case "smart": return new SmartPerson(); case "dumb": return new DumbPerson(); default: return null; } } } public interface Person { void doMath(); } public class SmartPerson implements Person { @Override public void doMath() { System.out.println("1 + 1 = 2"); } } public class DumbPerson implements Person { @Override public void doMath() { System.out.println("1 + 1 = 3"); } }
source share