Java Reference
In-Depth Information
public static Factory_2 getFactory()
{
synchronized (classLock)
{
if (factory == null)
{
factory = new Factory_2();
}
return factory;
}
}
public void recordWipMove()
{
// challenge!
}
// ...
}
The getFactory() code ensures that if a second thread begins to lazy-initialize the
singleton after another thread has begun the same initialization, the second thread will wait to
obtain the classLock object's monitor. When it obtains the monitor, the second thread will
find that the singleton is no longer null.
The wipMoves variable records the number of times that work in process ( WIP ) advances.
Every time a bin moves onto a new machine, the subsystem that causes or records the move
must call the factory singleton's recordWipMove() method.
CHALLENGE 8.3
Write the code for the recordWipMove() method of the Factory_2 class.
Recognizing Singleton
Unique objects are not uncommon. In fact, most objects in an application bear a unique
responsibility; why would you create two objects with identical responsibilities? Similarly,
nearly every class has a unique role. Why would you develop the same class twice? On the
other hand, singleton classes—classes that allow only a single instance—are relatively rare.
The fact that an object or a class is unique does not imply that the S INGLETON pattern is at
work. Consider the classes in Figure 8.1.
Search WWH ::




Custom Search