Design Patterns Java™ Workbook

(Michael S) #1
Chapter 18. Prototype

references to. Rather than using Object.clone() to create a new GUI object, it is safer to
instantiate the class you want and to set the new object's instance variables explicitly.


CHALLENGE 18.4


Write OzTextArea.clone() so that it copies a text area without relying on
a superclass implementation of clone().

After arranging for your prototypical GUI objects to copy themselves, your design is
complete. You have replaced the complete ComponentKit hierarchy with a single class,
UIKit. As with any abstract factory, you can create methods that build screens that are
independent of the look-and-feel of a specific component set.


For example, the following class constructs and displays a panel with cross-sales instructions
on a handheld device:


package com.oozinoz.ui;
import java.awt.;
import javax.swing.
;
public class ShowKit
{
public static JPanel crossSales(UIKit k)
{
JPanel p = new JPanel();
p.setLayout(new BorderLayout());
p.add(k.createButton("Clear"), "South");
OzTextArea t = k.createTextArea();
t.append(" 1) Consult the recommendation list.\n");
t.append(" 2) Establish customer interest.\n");
t.append(" 3) Close the sale.\n");
p.add(t, "Center");
return p;
}
public static void main(String[] args)
{
UIKit k = UIKit.handheld();
JPanel p = ShowKit.crossSales(k);
SwingFacade.launch(p, " Oozinoz Cross Sales");
}
}


This code launches a panel that is too tiny to show in this book. In practice, such an
application will also set up an action listener to react to a user's screen clicks.


Using Object.clone().........................................................................................................................


The Oozinoz application suite includes a visualization that shows users how material is
flowing through machines on the factory floor. Now the business wants a simulation version
of this screen to let the user experiment with releasing orders into the factory, changing
machine attributes, and altering other aspects of the factory's operation. A particular feature
your users want in the simulation is to be able to drag-and-drop a copy of a simulated

Free download pdf