The motivation for using Static Factory methods staes as:
The most obvious motivation for Replace Constructor with Factory
Method comes with replacing a type code with subclassing.You have an object that often is created with a type code but now
needs subclasses. The exact subclass is based on the type code.However, constructors can only return an instance of the object that
is asked for. So you need to replace the constructor with a factory
method.
Can anyone please explain this with code? And what does this type code mean?
Imagine we have a
Personclass with a field calledtypeto indicate if that person is a teacher or a student. This will be the type code.Now imagine we replace this type field with an object hierarchy:
Personclass with 2 subclassesTeacherandStudent.If I use the constructors then I can only create a specific type of person i.e.
new Teacher()ornew Student()but if I want a method that creates a different kind of person based on some logic then I can do: