Static Factory Method Pattern
Although Java's new C(...)
syntax for creating
new objects is straightforward, it causes
problems when used indiscriminately in large programs.
In Java, that syntax requires
the creating method to know the name of the class for that
new object.
That may sound reasonable for simple data types such as
UTC
, but what if there are two or more classes
that implement the UTC
interface?
What if choosing which class to use is complicated?
One of the classes that implements the UTC
interface might be preferred during the early phases of
a program's execution, but a different representation
might be preferred during later phases.
If users of the UTC
abstract data type
create new values of that type using the
new
operator, then every use
of that operator would need to be augmented by conditional
code that determines the current phase of the program
before deciding whether to create the new value via
new UTC1(...)
or new UTC2(...)
.
To give another example, suppose it becomes necessary to
improve the efficiency of a program, and someone concludes
its efficiency could be improved by creating at most one
UTC
object for any given combination of hour
and minute. Then every occurrence of new UTC1(h,m)
would have to be replaced by a fairly complicated computation
that determines whether a UTC
with hour and
minute components equal to h
and m
is already available. If so, it would use that previously created
UTC
. If not, it would create a new UTC
and enter that new UTC
into a database of
available UTC
values.
The computations implied by those two examples are too
complicated to be written out in full everywhere a new
UTC
value is needed.
Writing those computations out in many different places
would violate the programming principle that says
Don't repeat yourself.
Static factory methods solve the problem.
Instead of writing out the logic needed to decide
whether it is necessary to create a brand new object,
and to decide which representation to use for that object
if a new object is needed,
we can define a single static factory method that
encapsulates the necessary logic. Everyone who needs to
create new values of that data type can then call the
static factory method instead of writing code that
contains explicit uses of the new
syntax.