CS 635 Advanced Object-Oriented Design & Programming Spring Semester, 2002 Builder |
||
---|---|---|
© 2002, All Rights Reserved, SDSU & Roger Whitney San Diego State University -- This page last updated 21-Feb-02 |
Builder
Intent
Separate the construction of a complex object from its representation so that the same construction process can create different representations
Applicability
Use the Builder pattern when
Collaborations
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
Director
Java Example
public static void main(String argv[]) { SAXDriverExample handler = new SAXDriverExample(); // Use the default (non-validating) parser SAXParserFactory factory = SAXParserFactory.newInstance(); try { SAXParser saxParser = factory.newSAXParser(); saxParser.parse( new File("sample"), handler ); } catch (Throwable t) { t.printStackTrace(); } System.out.println( handler.root()); }
Smalltalk Example
| builder exampleDispatcher |
builder := SAXDriverExample new. exampleDispatcher := SAXDispatcher new contentHandler: builder. XMLParser processDocumentInFilename: 'page' beforeScanDo: [:parser | parser saxDriver:(exampleDispatcher); validate: true]. builder root.
Consequences