I'm familiar with the idea and benefits of a static factory method, as described in Joshua Bloch's Effective Java:
- Factory methods have names, so you can have more than one factory method with the same signature, unlike constructors.
- Factory methods don't have to create a new object; they can return a previously-created object. This is good for immutable objects or value objects.
- Factory methods can return an object of any subtype of their return type, unlike constructors.
Now I'm trying to explain static factory methods for someone who is learning Java and OO principles. She learns best from concrete scenarios instead of abstractions. If she can see the pattern at work, solving some problem, she'll get it. But she finds it harder to read an abstract list of characteristics like the above to understand how to apply the pattern.
Can you help me come up with a realistic example of using a static factory method, that makes its benefits clear, but which is still simple enough to show someone in an introductory Java class?
This person does have programming experience in PL/SQL but never got around to learning OOP patterns.