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 reverently believe that the Maker who made us all makes everything in New England but the weather. I dont know who makes that, but I think it must be raw apprentices in the weather-clerks factory who experiment and learn how.... In the spring I have counted one hundred and thirty-six different kinds of weather inside of four-and-twenty hours.”
—Mark Twain [Samuel Langhorne Clemens] (18351910)
“If all feeling for grace and beauty were not extinguished in the mass of mankind at the actual moment, such a method of locomotion as cycling could never have found acceptance; no man or woman with the slightest aesthetic sense could assume the ludicrous position necessary for it.”
—Ouida [Marie Louise De La Ramée] (18391908)
“With only one life to live we cant afford to live it only for itself. Somehow we must each for himself, find the way in which we can make our individual lives fit into the pattern of all the lives which surround it. We must establish our own relationships to the whole. And each must do it in his own way, using his own talents, relying on his own integrity and strength, climbing his own road to his own summit.”
—Hortense Odlum (1892?)