Java Reference
In-Depth Information
Creator
can provide a standard implementation for the factory method. That way
Creator
doesn't have to be an
abstract class or interface, but can be a full-blown class. The benefit is that you aren't required to subclass the
Creator
.
Product
can be implemented as an abstract class. Because the
Product
is a class, you can add implementations
for other methods.
The factory method can take a parameter. It can then create more than one type of
Product
based on the given
parameter. This decreases the number of factory methods needed.
Related Patterns
Related patterns include the following:
Abstract Factory (page 6) - Might use one or more factory methods.
Prototype (page 28) - Prevents subclassing of
Creator
.
Template Method (page 131) - Template methods usually call factory methods.
Data Access Object [CJ2EEP] - The Data Access Object pattern uses the Factory Method pattern to be able to
create specific instances of Data Access Objects without requiring knowledge of the specific underlying database.
Example
Note:
For a full working example of this code example, with additional supporting classes and/or a
RunPattern
class,
The following example uses the Factory Method pattern to produce an editor for the PIM. The PIM tracks a lot of
information, and there are many cases where users need an editor to create or modify data. The example uses
interfaces to improve the overall flexibility of the system.
The
Editable
interface defines a builder method,
getEditor
, which returns an
ItemEditor
interface. The
benefit is that any item can provide an editor for itself, producing an object that knows what parts of a business
object can change and how they can be changed. The only thing the user interface needs to do is use the
Editable
interface to get an editor.
Example 1.14
Editable.java
1. public interface Editable {
2. public ItemEditor getEditor();
3. }
The
ItemEditor
interface provides two methods:
getGUI
and
commitChanges
. The
getGUI
method is another
Factory Method—it returns a
JComponent
that provides a Swing GUI to edit the current item. This makes a very
flexible system; to add a new type of item, the user interface can remain the same, because it only uses the
Editable
and the
ItemEditor
interfaces.
The
JComponent
returned by
getGUI
can have anything in it required to edit the item in the PIM. The user
interface can simply the acquired
JComponent
in its editor window and use the
JComponent
functionality to edit
the item. Since not everything in an application needs to be graphical, it could also be a good idea to include a
getUI
method that would return an
Object
or some other non-graphical interface.
The second method,
commitChanges
, allows the UI to tell the editor that the user wants to finalize the changes he
or she has made.
Example 1.15
ItemEditor.java
1. import javax.swing.JComponent;
2. public interface ItemEditor {
3. public JComponent getGUI();
4. public void commitChanges();
5. }