If you look in the javax.xml.transform package, you'll see TransformerFactory. It has a newInstance() method which produces a TransformerFactory. This is a classic static factory method; read its documentation and you will see why it exists (namely to aid in producing Transformers of classes only known at run time).
Now look at the newTransformer() method. This is a factory method, but this time it's an instance method. Why? Because the TransformerFactory that the newInstance() method produced belongs to some subclass of javax.xml.TransformerFactory, a subclass which knows how to produce a Transformer of the desired class.
Confused? I wouldn't be surprised. Let's suppose that we configured things to say that the Saxon transformation package should be used. Then we first use the standard javax.xml.TransformerFactory by calling its newInstance() method. This returns an instance of a class from the Saxon product which is a subclass of javax.xml.TransformerFactory. Next we use that instance by calling its newTransformer() method, and that returns a Saxon transformer.
So why is that better than a constructor? Well, this way we write our program to do XML transformation, and later we can decide to use Saxon instead of the built-in transformer, without having to change anything. In particular, we didn't have to write a constructor to create an instance of the Saxon transformer. We didn't even need to know that Saxon existed when we wrote the program, and yet we can still decide to use it.
Joined: Jan 16, 2009
Thanks for that explanation. I was able to understand how static and instance factory methods are better than constructors. I am also trying to understand the difference between static and instance factory methods so I know when to use them.
One difference is that static factory methods can return subtypes of their class while instance factory methods can't. Right/Wrong?
Second difference, static factory methods are capable of returning data types that are only known at runtime and instance factory methods are not. Right/Wrong?