90 likes | 110 Views
The builder pattern separates the construction process of a complex object from its representation, allowing for different representations to be created. This pattern is useful for creating flexible and independent object construction processes.
E N D
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 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. 2) The baseball player tells the designer what he wants. Director 1) A baseball player wants some new furniture. He calls his interior designer. Concrete Builder1 Concrete Builder3 Concrete Builder2 4) The baseball player gets the chair produced by the builder and his tools. Product Client Client (w/ Product) Builder – Example 1
Designer MakeNewFurniture() Client While (want==newfurniture){ Getnewfurniture} Desk Chair Tank Builder – Example 1 UML Builder Furniture Maker BuildFurniture() ChairBuilder DeskBuilder TankBuilder BuildFurniture() GetDesk() BuildFurniture() GetChair() BuildFurniture() GetTank() Source: GOF
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
2) Director Notifies the Builder whenever a part of the product should be built Director Builder 3) Builder handles requests from the director and adds parts to the product Construct() BuildPart() Concrete Builder BuildPart()GetResult() for all objects in structure { Builder-->BuildPart( )} Product 4) Client retrieves the product from the builder 1) The Client creates the Director object and configures it with the desired Builder Object Builder – The Steps Source: GOF
Builder TextConverter RTFReader ParseRTF() ASCIIConverter TeXConverter TextWidgetConverter ConvertCharacter(char) ConvertFontChange(Font) ConvertParagraph() GetTeXText() ConvertCharacter(char) GetASCIIText() ConverCharacter(cahr) ConvertFontChange(Font) ConvertParagraph() GetTextWidget() Client While (t=get the next token){Switch t.Type{ CHAR: Builder ConvertCharacter(t.Char) FONT: Builder ConvertFontChange(t.Font) PARA: BuilderConvertParagraph() }} TeXText ASCIIText TextWidget Builder – Example 2 Source: GOF