Let’s hear it for BUILDER!!!!!!!
Builder – The Intent \ Description To separate the construction of a complex object from its representation so that the same construction process can create different representations Source: GOF
Builder – The Intent – In English A client uses the builder pattern like an individual would use an interior designer and furniture maker to build furniture - the individual (Client) tells the designer what he wants, and the designer (Director), the furniture maker (Builder), and his tool (Concrete builders) create the furniture (Product)
Builder – Example 1 Director 2) The baseball player tells the designer what he wants. Concrete Builder2 Concrete Builder3 Concrete Builder1 Client 1) A baseball player wants some new furniture. He calls his interior designer. Builder 3) The designer tells the furniture maker to build a chair. Note that the furniture maker could have also built a desk or a tank. Product Client (w/ Product) 4) The baseball player gets the chair produced by the builder and his tools.
Builder – Example 1 UML Client While (want==newfurniture){ Getnewfurniture} Source: GOF Designer MakeNewFurniture() Furniture Maker ChairBuilderDeskBuilderTankBuilder BuildFurniture() GetChair () BuildFurniture() GetDesk () BuildFurniture() GetTank () Builder Chair Desk Tank BuildFurniture()
Why Use Builder? Use the builder pattern when: –The algorithm for creating a complex object should be independent of the parts that make up the object and how they are assembled –The construction process must allow different representations for the object that’s constructed Builder is very useful because it allows the program to create a flexible number of objects – you can add or delete objects as necessary Source: GOF
Builder – The Steps Source: GOF 1) The Client creates the Director object and configures it with the desired Builder Object for all objects in structure { Builder-->BuildPart( )} Director 2) Director Notifies the Builder whenever a part of the product should be built Construct() 3) Builder handles requests from the director and adds parts to the product Builder BuildPart() Product 4) Client retrieves the product from the builder Concrete Builder BuildPart() GetResult()
Builder – Example 2 Client While (t=get the next token){Switch t.Type{ CHAR: Builder ConvertCharacter(t.Char) FONT: Builder ConvertFontChange(t.Font) PARA: Builder ConvertParagraph() }} Source: GOF RTFReader ParseRTF() TextConverter ASCIIConverterTeXConverterTextWidgetConverter ConvertCharacter(char) GetASCIIText() ConvertCharacter(char) ConvertFontChange(Fo nt) ConvertParagraph() GetTeXText() ConverCharacter(cahr) ConvertFontChange(Font) ConvertParagraph() GetTextWidget() Builder ASCIIText TeXText TextWidget