Design Patterns Java™ Workbook

(Michael S) #1
Chapter 18. Prototype

Figure 18.4. X and Y coordinates in a bay are measured as offsets from the northwest
corner of the bay.

You have included a clone_1() method with MachineSimulator. (The underscore in
the method name indicates that we will later alter this method.) The point of the method is
that you can use clone_1() as a factory method, producing a new machine simulation
object from a prototype the user clicks on. Your initial code for
MachineSimulator.clone_1() is:


public Object clone_1()
{
try
{
return super.clone();
}
catch (CloneNotSupportedException e)
{
// this shouldn't happen, since we are Cloneable
throw new InternalError();
}
}


This code makes the clone_1() method public, and we shall soon see that we need to
modify this code to create a proper copy. First, though, note that MachineSimulator
implements Cloneable. This interface is a marker that Object.clone() checks to ensure
that the clone() method is appropriate for a subclass. Without this declaration, the
clone_1() method would throw a CloneNotSupportedException when it called
super.clone(). The possibility that this exception will be thrown forces you to enclose
the call in a try/catch statement. However, you are confident that this exception will never
be thrown; if it is thrown, you decide to throw in turn an InternalError error, which is
what the frequently used ArrayList class does in this situation.

Free download pdf