Singleton Pattern - Example of Use With The Factory Method Pattern

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:

    If the factory people outside the colleges live under the discipline of narrow means, the people inside live under almost every other kind of discipline except that of narrow means—from the fruity austerities of learning, through the iron rations of English gentlemanhood, down to the modest disadvantages of occupying cold stone buildings without central heating and having to cross two or three quadrangles to take a bath.
    Margaret Halsey (b. 1910)

    Protestantism has the method of Jesus with His secret too much left out of mind; Catholicism has His secret with His method too much left out of mind; neither has His unerring balance, His intuition, His sweet reasonableness. But both have hold of a great truth, and get from it a great power.
    Matthew Arnold (1822–1888)

    It may be tempting to focus on the fact that, even among those who support equality, men’s involvement as fathers remains a far distance from what most women want and most children need. Yet it is also important to acknowledge how far and how fast many men have moved towards a pattern that not long ago virtually all men considered anathema.
    Katherine Gerson (20th century)