Class 2 |
Intermediate Java 30-IT-397 |
|
Singleton Pattern
-
Resource: http://www.patterndepot.com/put/8/Singleton.PDF
-
The singleton pattern allows you to insure that a class can only be instantiated
one time.
-
What you need to do:
-
Declare the constructor private. Thus, the class cannot be instantiated
by anyone but itself, since only it has access to the constructor.
-
A static attribute of the same type as the class, that holds the
single object of the class.
-
Provide a static method that returns the single instance of the class.
Why a static method? Thus, it will need
to have a return type of the class itself. It should first check
the static attribute (above) to see if the object has been instantiated
- it is likely that it will not be the first time it is called.
-
If it has been instantiated, simply return that object from the static
attribute.
-
If not, instantiate an object, save it to the static variable listed above,
and return it.
-
This is most commonly used with single instances, but you can maintain
a small number of instances the same way.
-
Example.
Behavioral Patterns

Created by: Brandan Jones
December 17, 2001