Applied Design Patterns with Java

Creational :: Prototype (117) {C ch 8}

Intent
Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.

Motivation

Consider an editor for music scores that customizes a framework for graphical editors and adds new objects as notes, rests, and staves. The editor framework may have a palette of tools for adding these music objects to the score. The palette would also include tools for selecting, moving, and otherwise manipulating music objects.

Assume the framework provides an abstract Graphic class for graphical components, like notes and staves, as well as an abstract Tool class for defining tools like those in the palette. The framework also predefines a GraphicTool subclass for tools that create instances of graphical objects and add them to the document.

However, the classes for notes and staves are specific to an application, but the GraphicTool class belongs to the framework. GraphicTool doesn't know how to create instances of our music classes to add to the score. If GraphicTool were subclassed for each kind of music object, that would produce lots of subclasses that differ only in the kind of music object they instantiate. How can the framework use composition to parameterize instances of GraphicTool by the class of Graphic they need to create?

Let GraphicTool create a new Graphic by copying or "
cloning" an instance of a Graphic subclass. We call this instance a Prototype. GraphicTool is parameterized by the Prototype it should clone and add to the document. If all Graphic subclasses support a Clone operation, then the GraphicTool can clone any kind of Graphic.

Thus, each tool for creating a music object is an instance of GraphicTool that's initialized with a different prototype. Each GraphicTool instance will produce a music object by cloning its prototype and adding the clone to the score.



Use the Prototype pattern to reduce the number of classes even further. The separate classes for whole notes and half notes are probably unnecessary. Instead they could be instances of the same class initialized with different bitmaps and durations. A tool for creating whole notes becomes just a GraphicTool whose Prototype is a MusicalNote initialized to be a whole note. This can reduce the number of classes in the system dramatically. It also makes it easier to add a new kind of note to the music editor.

Catalog Creational Prev Next