Java Reference
In-Depth Information
public
public class
class EnumList
EnumList {
enum
enum State {
ON , OFF , UNKNOWN
}
public
public static
static void
void main ( String [] args ) {
for
for ( State i : State . values ()) {
System . out . println ( i );
}
}
}
The output of the EnumList program is, of course:
ON
OFF
UNKNOWN
Enforcing the Singleton Pattern
Problem
You want to be sure there is only one instance of your class in a given Java Virtual Machine.
Solution
Make your class enforce the Singleton Pattern (see page 127 of the topic Design Patterns ),
primarily by having only a private constructor(s).
Discussion
It is often useful to ensure that only one instance of a class gets created, usually to funnel all
requests for some resource through a single point. An example of a Singleton from the stand-
ard API is java.lang.Runtime ; you cannot create instances of Runtime , you simply ask for
a reference by calling the static method Runtime.getRuntime() . Singleton is also an ex-
ample of a design pattern that can be easily implemented.
The easiest implementation consists of a private constructor and a field to hold its result, and
a static accessor method with a name like getInstance() .
Search WWH ::




Custom Search