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:

    The medieval university looked backwards; it professed to be a storehouse of old knowledge.... The modern university looks forward, and is a factory of new knowledge.
    Thomas Henry Huxley (1825–1895)

    Frankly, I adore your catchy slogan, “Adoption, not Abortion,” although no one has been able to figure out, even with expert counseling, how to use adoption as a method of birth control, or at what time of the month it is most effective.
    Barbara Ehrenreich (b. 1941)

    A two-week-old infant cries an average of one and a half hours every day. This increases to approximately three hours per day when the child is about six weeks old. By the time children are twelve weeks old, their daily crying has decreased dramatically and averages less than one hour. This same basic pattern of crying is present among children from a wide range of cultures throughout the world. It appears to be wired into the nervous system of our species.
    Lawrence Kutner (20th century)