Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Builder pattern
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
{{Short description|Design pattern in object-oriented programming}} The '''builder pattern''' is a [[Software design pattern|design pattern]] that provides a flexible solution to various object creation problems in [[object-oriented programming]]. The builder pattern [[Separation of concerns|separates]] the construction of a complex object from its representation. It is one of the 23 classic design patterns described in the book ''[[Design Patterns]]'' and is sub-categorized as a [[creational pattern]].{{sfn|Gamma|Helm|Johnson|Vlissides|1994|page=97}} ==Overview== The builder design pattern solves problems like:<ref>{{cite web|title=The Builder design pattern - Problem, Solution, and Applicability|url=http://w3sdesign.com/?gr=c02&ugr=proble|website=w3sDesign.com|access-date=2017-08-13}}</ref> * How can a class (the same construction process) create different representations of a complex object? * How can a class that includes creating a complex object be simplified? Creating and assembling the parts of a complex object directly within a class is inflexible. It commits the class to creating a particular representation of the complex object and makes it impossible to change the representation later independently from (without having to change) the class. The builder design pattern describes how to solve such problems: * Encapsulate creating and assembling the parts of a complex object in a separate <code>Builder</code> object. * A class delegates object creation to a <code>Builder</code> object instead of creating the objects directly. A class (the same construction process) can delegate to different <code>Builder</code> objects to create different representations of a complex object. ==Definition== The intent of the builder design pattern is to separate the construction of a complex object from its representation. By doing so, the same construction process can create different representations.{{sfn|Gamma|Helm|Johnson|Vlissides|1994|page=97}} == Advantages == Advantages of the builder pattern include:<ref name=":0">{{Cite web|url = https://www.classes.cs.uchicago.edu/archive/2010/winter/51023-1/presentations/ricetj_builder.pdf|title = Index of /archive/2010/winter/51023-1/presentations|website = www.classes.cs.uchicago.edu|access-date = 2016-03-03}}</ref> * Allows you to vary a product's internal representation. * Encapsulates code for construction and representation. * Provides control over the steps of the construction process. == Disadvantages == Disadvantages of the builder pattern include:<ref name=":0" /> * A distinct ConcreteBuilder must be created for each type of product. * Builder classes must be mutable. * May hamper/complicate dependency injection. * In many [[Void safety|null-safe]] languages, the builder pattern defers [[Compile time|compile-time]] errors for unset fields to [[Execution (computing)#Runtime|runtime]]. ==Structure== === UML class and sequence diagram === [[File:w3sDesign Builder Design Pattern UML.jpg|frame|none|A sample UML class and sequence diagram for the builder design pattern.<ref>{{cite web|title=The Builder design pattern - Structure and Collaboration|url=http://w3sdesign.com/?gr=c02&ugr=struct|website=w3sDesign.com|access-date=2017-08-12}}</ref>]] In the above [[Unified Modeling Language|UML]] [[class diagram]], the <code>Director</code> class doesn't create and assemble the <code>ProductA1</code> and <code>ProductB1</code> objects directly. Instead, the <code>Director</code> refers to the <code>Builder</code> interface for building (creating and assembling) the parts of a complex object, which makes the <code>Director</code> independent of which concrete classes are instantiated (which representation is created). The <code>Builder1</code> class implements the <code>Builder</code> interface by creating and assembling the <code>ProductA1</code> and <code>ProductB1</code> objects. <br/> The [[Unified Modeling Language|UML]] [[sequence diagram]] shows the run-time interactions: The <code>Director</code> object calls <code>buildPartA()</code> on the <code>Builder1</code> object, which creates and assembles the <code>ProductA1</code> object. Thereafter, the <code>Director</code> calls <code>buildPartB()</code> on <code>Builder1</code>, which creates and assembles the <code>ProductB1</code> object. === Class diagram === [[Image:Builder UML class diagram.svg|500px|center|Builder Structure]] ; Builder : Abstract interface for creating objects (product). ; ConcreteBuilder : Provides implementation for Builder. It is an [[factory (software concept)|object able to construct other objects]]. Constructs and assembles parts to build the objects. == Examples == A [[C Sharp (programming language)|C#]] example: <syntaxhighlight lang="csharp"> /// <summary> /// Represents a product created by the builder. /// </summary> public class Bicycle { public Bicycle(string make, string model, string colour, int height) { Make = make; Model = model; Colour = colour; Height = height; } public string Make { get; set; } public string Model { get; set; } public int Height { get; set; } public string Colour { get; set; } } /// <summary> /// The builder abstraction. /// </summary> public interface IBicycleBuilder { Bicycle GetResult(); string Colour { get; set; } int Height { get; set; } } /// <summary> /// Concrete builder implementation. /// </summary> public class GTBuilder : IBicycleBuilder { public Bicycle GetResult() { return Height == 29 ? new Bicycle("GT", "Avalanche", Colour, Height) : null; } public string Colour { get; set; } public int Height { get; set; } } /// <summary> /// The director. /// </summary> public class MountainBikeBuildDirector { private IBicycleBuilder _builder; public MountainBikeBuildDirector(IBicycleBuilder builder) { _builder = builder; } public void Construct() { _builder.Colour = "Red"; _builder.Height = 29; } public Bicycle GetResult() { return this._builder.GetResult(); } } public class Client { public void DoSomethingWithBicycles() { var director = new MountainBikeBuildDirector(new GTBuilder()); // Director controls the stepwise creation of product and returns the result. director.Construct(); Bicycle myMountainBike = director.GetResult(); } } </syntaxhighlight> A Java example:<syntaxhighlight lang="java" line="1"> public class Employee { // Required parameters private final String name; private final int id; // Optional parameters private final String department; private final double salary; // Private constructor private Employee(Builder builder) { this.name = builder.name; this.id = builder.id; this.department = builder.department; this.salary = builder.salary; } // Static nested Builder class public static class Builder { private final String name; private final int id; private String department = "General"; // default value private double salary = 0.0; // default value public Builder(String name, int id) { this.name = name; this.id = id; } public Builder department(String department) { this.department = department; return this; } public Builder salary(double salary) { this.salary = salary; return this; } public Employee build() { return new Employee(this); } } @Override public String toString() { return "Employee{name='" + name + "', id=" + id + ", department='" + department + "', salary=" + salary + '}'; } } public class Main { public static void main(String[] args) { Employee emp = new Employee.Builder("Alice", 101) .department("Engineering") .salary(90000.0) .build(); System.out.println(emp); } } </syntaxhighlight>The Director assembles a bicycle instance in the example above, delegating the construction to a separate builder object that has been given to the Director by the Client. == See also == * [[Currying]] ==Notes== {{Reflist}} ==References== * {{cite book |last1=Gamma |first1=Erich |last2=Helm |first2=Richard |last3=Johnson|first3=Ralph |last4=Vlissides |first4=John |title=Design Patterns: Elements of Reusable Object-Oriented Software |publisher=Addison-Wesley |year=1994 |isbn=0-201-63361-2 |author1-link=Erich Gamma |author2-link=Richard Helm |author3-link=Ralph Johnson (computer scientist)|author4-link=John Vlissides |title-link=Design Patterns }} ==External links== {{Wikibooks|Computer Science Design Patterns|Builder|Builder implementations in various languages}} {{Design Patterns Patterns}} {{Auth}} [[Category:Software design patterns]] [[Category:Articles with example Java code]]
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)
Pages transcluded onto the current version of this page
(
help
)
:
Template:Auth
(
edit
)
Template:Cite book
(
edit
)
Template:Cite web
(
edit
)
Template:Design Patterns Patterns
(
edit
)
Template:Reflist
(
edit
)
Template:Sfn
(
edit
)
Template:Short description
(
edit
)
Template:Sister project
(
edit
)
Template:Wikibooks
(
edit
)