Example of Use With The Factory Method Pattern
The singleton pattern is often used in conjunction with the factory method pattern to create a system-wide resource whose specific type is not known to the code that uses it. An example of using these two patterns together is the Java Abstract Window Toolkit (AWT).
java.awt.Toolkit
is an abstract class that binds the various AWT components to particular native toolkit implementations. The Toolkit
class has a Toolkit.getDefaultToolkit
factory method that returns the platform-specific subclass of Toolkit
. The Toolkit
object is a singleton because the AWT needs only a single object to perform the binding and the object is relatively expensive to create. The toolkit methods must be implemented in an object and not as static methods of a class because the specific implementation is not known by the platform-independent components. The name of the specific Toolkit
subclass used is specified by the "awt.toolkit" environment property accessed through System.getProperties
.
The binding performed by the toolkit allows, for example, the backing implementation of a java.awt.Window
to bind to the platform-specific java.awt.peer.WindowPeer
implementation. Neither the Window
class nor the application using the window needs to be aware of which platform-specific subclass of the peer is used.
Read more about this topic: Singleton Pattern
Famous quotes containing the words factory, method and/or pattern:
“I cannot believe that our factory system is the best mode by which men may get clothing. The condition of the operatives is becoming every day more like that of the English; and it cannot be wondered at, since, as far as I have heard or observed, the principal object is, not that mankind may be well and honestly clad, but, unquestionably, that the corporations may be enriched.”
—Henry David Thoreau (18171862)
“I have usually found that there was method in his madness.
Some folk might say there was madness in his method.”
—Sir Arthur Conan Doyle (18591930)
“Art is the imposing of a pattern on experience, and our aesthetic enjoyment is recognition of the pattern.”
—Alfred North Whitehead (18611947)