The item discusses several advantages of static factory methods:
- their self documenting nature, and their extra flexibility when construction parameter sets are ambiguous
- their use with object caches like the GoF Flyweight pattern and other "instance-controlled" classes (a term which is new to me although the author impies that it is idiomatic)
- their use with derived class hierarchies particularly for implementation hiding where the concrete instance returned by the factory method is of a non-public type, this allows implementation variation depending on construction arguments or other mechanisims such as being able to return types which have been registered at runtime in a so called "service provider framework"
- they may be used to simplify parameterized type construction by eliminating the duplication of type parameters by the user by letting the compiler deduce the types;
- if all construction is done via static factories and all constructors are non-public then users cannot derive from the classes in their packages - although this would be an advantage if it was desired by the class designer
- without careful documentation or standardized naming, it isn't obvious to users that the factory methods are what they are and should be used to instantiate objects of the class
I disagree a little with the implied similarity to items in this book and design patterns, the first two items (which is as far as I have read) are not design patterns just examples of idiomatic Java usage. Design patterns deal with relationships between classes in a mostly language independant way, whereas this book and similar ones for C++ rarely give any advice on how classes should collaborate with each other. Nevertheless the information is valuable and I am only querying the references to the GoF book that imply these items are design patterns.
Bill Somerville
No comments:
Post a Comment