Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Realistic use case for static factory method?

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.

like image 716
Bill Karwin Avatar asked Nov 16 '10 16:11

Bill Karwin


1 Answers

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:

  • There are multiple static methods with different names like createEmptyBorder() and createEtchedBorder().
  • These methods will return previously created objects when possible. It's quite frequent that the same border would be used throughout an application.
  • Border itself is actually an interface, so all objects created through this factory are actually classes which implement this interface.
like image 200
Erick Robertson Avatar answered Sep 25 '22 04:09

Erick Robertson