Design Patterns Java™ Workbook

(Michael S) #1
Appendix B. Solutions

Singleton (Chapter 8)................................................................................................................................


SOLUTION 8.1.......................................................................................................................................

To prevent other developers from instantiating your class, create a single constructor with
private visibility. Note that if you create other, nonprivate constructors or create no
constructors at all, other developers will likely be able to reinstantiate your class.


SOLUTION 8.2.......................................................................................................................................

As Design Patterns says, "You might not have enough information to instantiate every
singleton at static initialization time. A singleton might require values that are computed later
in the program's execution" (p. 130). When a Factory singleton is born, for example, it
might have to establish connections with machine drivers, to set up planners, and to initialize
a simulation of itself.


SOLUTION 8.3.......................................................................................................................................

Your solution should eliminate the possibility of confusion that can occur when two threads
call the recordWipMove() method at approximately the same time:


public void recordWipMove()
{
synchronized (classLock)
{
wipMoves++;
}
}


Is it possible that a thread might activate in the middle of an increment operation? Even if
you're certain that the answer is no, it's a good policy to carefully restrict access to
a singleton's data in a multithreaded application.


Multithreaded applications often fail because their developers do not understand
the mechanics of synchronization or do not foresee subtle problems that can occur. If you are
working with a multithreaded Java application, I heartily recommend familiarizing yourself
with the information in Concurrent Programming in Java™ (Lea 2000).


SOLUTION 8.4.......................................................................................................................................

OurBiggestRocket This class has an inappropriate name. You should model attributes,
such as "biggest," with attributes, not with class names. If a developer
must sustain this class, perhaps it is a singleton.
TopSalesAssociate This class has the same problem as OurBiggestRocket.


Math This class is a utility, with all static methods and no instances. It is not
a singleton.


System This is a utility.


PrintStream Although the System.out object is a PrintStream object with
unique responsibilities, it is not a unique instance of PrintStream,
which is not a singleton class.

Free download pdf