SDSU Advanced Object-Oriented Design & Programming
Spring Semester, 2005
Prototype & Builder
Previous     Lecture Notes Index     Next     
© 2005 All Rights Reserved, SDSU & Roger Whitney
San Diego State University -- This page last updated April 19, 2005

CS 635 Advanced Object-Oriented Design & Programming

Spring Semester, 2005

Doc 15 Prototype & Builder





Copying Issues    

Shallow Copy Verse Deep Copy    

Cloning Issues    


Implementation Issues    



Example – XML Parser    



Copyright ©, All rights reserved. 2005 SDSU & Roger Whitney, 5500 Campanile Drive, San Diego, CA 92182-7700 USA. OpenContent ( ) license defines the copyright on this document.




Design Patterns: Elements of Reusable Object-Oriented Software, Gamma, Helm, Johnson, Vlissides, Addison-Wesley, 1995, pp. 117-126, 97-106


The Design Patterns Smalltalk Companion, Alpert, Brown, Woolf, Addision-Wesley, 1998, pp. 77-90, 47-62






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





Use the Prototype pattern when


  1. A system should be independent of how its products are created, composed, and represented; and


  1. When the classes to instantiate are specified at run-time; or


  1. To avoid building a class hierarchy of factories that parallels the class hierarchy of products; or


  1. When instances of a class can have one of only a few different combinations of state.


It may be easier to have the proper number of prototypes and clone them rather than instantiating the class manually each time




Insurance Example


Insurance agents start with a standard policy and customize it



Two basic strategies:


  1. Copy the original and edit the copy


  1. Store only the differences between original and the customize version in a decorator




Copying Issues

Shallow Copy Verse Deep Copy


Original Objects




Shallow Copy







Shallow Copy Verse Deep Copy


Original Objects




Deep Copy







Shallow Copy Verse Deep Copy


Original Objects





Deeper Copy





Cloning Issues

How to in C++ - Copy Constructors


class Door




        Door( const Door&);


        virtual Door* clone() const;


        virtual void Initialize( Room*, Room* );

        // stuff not shown


        Room* room1;

        Room* room2;



Door::Door ( const Door& other ) //Copy constructor


    room1 = other.room1;

    room2 = other.room2;



Door* Door::clone()  const


    return new Door( *this );






How to in Java - Object clone()


protected Object clone() throws CloneNotSupportedException


Default is shallow copy


Returns: A clone of this Object.


Throws: OutOfMemoryError


Throws: CloneNotSupportedException


class Door implements Cloneable {

    public void Initialize( Room a, Room b)

        { room1 = a; room2 = b; }


    public Object clone() throws

                     CloneNotSupportedException {

        // modify this method for deep copy

        // no need to implement this method for shallow copy

        return super.clone();


    Room room1;

    Room room2;





VisualWorks Smalltalk



    Does a shallowCopy of the receiver



    ^self shallowCopy postCopy


    “Template method for copy”


Copy is the primary method for copying an object


Classes override postCopy to do more than shallow copyDoor


Smalltalk.CS635 defineClass: #Door

    superclass: #{Core.Object}

    indexedType: #none

    private: false

    instanceVariableNames: 'room1 room2 '



    room1 := room1 copy.

    room2 := room2 copy.






  1. Adding and removing products at run-time


  1. Specifying new objects by varying values


  1. Specifying new objects by varying structure


  1. Reducing subclassing (from factory method)


  1. Configuring an application with classes dynamically



Implementation Issues


  1. Using a prototype manager


  1. Implementing the Clone operation


  1. Initializing clones







Separate the construction of a complex object from its representation so that the same construction process can create different representations




Use the Builder pattern when


  1. The algorithm for creating a complex object should be independent of the parts that make up the object and how they're assembled


  1. The construction process must allow different representations for the object that's constructed







The client creates the Director object and configures it with the desired Builder object


Director notifies the builder whenever a part of the product should be built


Builder handles requests from the director and adds parts to the product


The client retrieves the product from the builder







Example – XML Parser



XML Parser


Abstract Builder Class

XML.SAXDriver (Smalltalk)

org.xml.sax.helpers.DefaultHandler (Java)

DefaultHandler (C++)


Concrete Builder Class

Your subclass of the abstract builder



    Your code that uses the tree built




Java Example


    public static void main(String argv[])


        SAXDriverExample handler = new SAXDriverExample();


          // Use the default (non-validating) parser

        SAXParserFactory factory = SAXParserFactory.newInstance();



            SAXParser saxParser = factory.newSAXParser();

            saxParser.parse( new File("sample"), handler );


        catch (Throwable t)




        System.out.println( handler.root());





Smalltalk Example


| builder exampleDispatcher |


builder := SAXDriverExample new.

exampleDispatcher := SAXDispatcher new contentHandler: builder.


    processDocumentInFilename: 'page'


        [:parser |



            validate: true].

builder root.







  1. It lets you vary a product's internal representation


  1. It isolates code for construction and representation


  1. It gives you finer control over the construction process






  1. Assembly and construction interface


Builder may have to pass parts back to director, who will then pass them back to builder


  1. Why no abstract classes for products


  1. Empty methods as default in Builder


Previous     visitors since April 19, 2005     Next