I'm familiar with the idea and benefits of a static factory method, as described in Joshua Bloch's Effective Java:
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.
Use javax.swing.BorderFactory
as an example of all three points.
This class is used to make borders for swing objects. These border objects can be easily re-used, and this factory method allows for this. Here is the javadoc. This factory is a great example of all three points:
createEmptyBorder()
and createEtchedBorder()
.Border
itself is actually an interface, so all objects created through this factory are actually classes which implement this interface.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With