Builder pattern

Last updated

The builder pattern is a design pattern designed to provide a flexible solution to various object creation problems in object-oriented programming. The intent of the builder design pattern is to separate the construction of a complex object from its representation. It is one of the Gang of Four design patterns.

Contents

Overview

The Builder design pattern is one of the Design Patterns [1] that describe how to solve recurring design problems in object-oriented software.

The Builder design pattern solves problems like: [2]

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:

A class (the same construction process) can delegate to different Builder 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. [1]

Advantages

Advantages of the Builder pattern include: [3]

Disadvantages

Disadvantages of the Builder pattern include: [3]

Structure

UML class and sequence diagram

A sample UML class and sequence diagram for the Builder design pattern. W3sDesign Builder Design Pattern UML.jpg
A sample UML class and sequence diagram for the Builder design pattern.

In the above UML class diagram, the Director class doesn't create and assemble the ProductA1 and ProductB1 objects directly. Instead, the Director refers to the Builder interface for building (creating and assembling) the parts of a complex object, which makes the Director independent of which concrete classes are instantiated (which representation is created). The Builder1 class implements the Builder interface by creating and assembling the ProductA1 and ProductB1 objects.
The UML sequence diagram shows the run-time interactions: The Director object calls buildPartA() on the Builder1 object, which creates and assembles the ProductA1 object. Thereafter, the Director calls buildPartB() on Builder1, which creates and assembles the ProductB1 object.

Class diagram

Builder Structure Builder UML class diagram.svg
Builder Structure
Builder
Abstract interface for creating objects (product).
ConcreteBuilder
Provides implementation for Builder. It is an object able to construct other objects. Constructs and assembles parts to build the objects.

Examples

A C# example:

/// <summary>/// Represents a product created by the builder./// </summary>publicclassBicycle{publicBicycle(stringmake,stringmodel,stringcolour,intheight){Make=make;Model=model;Colour=colour;Height=height;}publicstringMake{get;set;}publicstringModel{get;set;}publicintHeight{get;set;}publicstringColour{get;set;}}/// <summary>/// The builder abstraction./// </summary>publicinterfaceIBicycleBuilder{BicycleGetResult();stringColour{get;set;}intHeight{get;set;}}/// <summary>/// Concrete builder implementation./// </summary>publicclassGTBuilder:IBicycleBuilder{publicBicycleGetResult(){returnHeight==29?newBicycle("GT","Avalanche",Colour,Height):null;}publicstringColour{get;set;}publicintHeight{get;set;}}/// <summary>/// The director./// </summary>publicclassMountainBikeBuildDirector{privateIBicycleBuilder_builder;publicMountainBikeBuildDirector(IBicycleBuilderbuilder){_builder=builder;}publicvoidConstruct(){_builder.Colour="Red";_builder.Height=29;}publicBicycleGetResult(){returnthis._builder.GetResult();}}publicclassClient{publicvoidDoSomethingWithBicycles(){vardirector=newMountainBikeBuildDirector(newGTBuilder());// Director controls the stepwise creation of product and returns the result.director.Construct();BicyclemyMountainBike=director.GetResult();}}

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

Related Research Articles

<i>Design Patterns</i> 1994 software engineering book

Design Patterns: Elements of Reusable Object-Oriented Software (1994) is a software engineering book describing software design patterns. The book was written by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, with a foreword by Grady Booch. The book is divided into two parts, with the first two chapters exploring the capabilities and pitfalls of object-oriented programming, and the remaining chapters describing 23 classic software design patterns. The book includes examples in C++ and Smalltalk.

<span class="mw-page-title-main">Abstract factory pattern</span> Software design pattern

The abstract factory pattern in software engineering is a design that provides a way to create families of related objects without imposing their concrete classes, by encapsulating a group of individual factories that have a common theme without specifying their concrete classes. According to this pattern, a client software component creates a concrete implementation of the abstract factory and then uses the generic interface of the factory to create the concrete objects that are part of the family. The client does not know which concrete objects it receives from each of these internal factories, as it uses only the generic interfaces of their products. This pattern separates the details of implementation of a set of objects from their general usage and relies on object composition, as object creation is implemented in methods exposed in the factory interface.

The bridge pattern is a design pattern used in software engineering that is meant to "decouple an abstraction from its implementation so that the two can vary independently", introduced by the Gang of Four. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.

<span class="mw-page-title-main">Flyweight pattern</span> Software design pattern for objects

In computer programming, the flyweight software design pattern refers to an object that minimizes memory usage by sharing some of its data with other similar objects. The flyweight pattern is one of twenty-three well-known GoF design patterns. These patterns promote flexible object-oriented software design, which is easier to implement, change, test, and reuse.

In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by creating objects by calling a factory method—either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes—rather than by calling a constructor.

The prototype pattern is a creational design pattern in software development. It is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. This pattern is used to avoid subclasses of an object creator in the client application, like the factory method pattern does, and to avoid the inherent cost of creating a new object in the standard way when it is prohibitively expensive for a given application.

In software engineering, the composite pattern is a partitioning design pattern. The composite pattern describes a group of objects that are treated the same way as a single instance of the same type of object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.

In object-oriented programming, the decorator pattern is a design pattern that allows behavior to be added to an individual object, dynamically, without affecting the behavior of other objects from the same class. The decorator pattern is often useful for adhering to the Single Responsibility Principle, as it allows functionality to be divided between classes with unique areas of concern as well as to the Open-Closed Principle, by allowing the functionality of a class to be extended without being modified. Decorator use can be more efficient than subclassing, because an object's behavior can be augmented without defining an entirely new object.

In software engineering, the mediator pattern defines an object that encapsulates how a set of objects interact. This pattern is considered to be a behavioral pattern due to the way it can alter the program's running behavior.

In software design and engineering, the observer pattern is a software design pattern in which an object, named the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.

In knowledge representation and ontology components, including for object-oriented programming and design, is-a is a subsumption relationship between abstractions, wherein one class A is a subclass of another class B . In other words, type A is a subtype of type B when A's specification implies B's specification. That is, any object that satisfies A's specification also satisfies B's specification, because B's specification is weaker.

In software engineering, creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or in added complexity to the design. Creational design patterns solve this problem by somehow controlling this object creation.

In class-based, object-oriented programming, a constructor is a special type of function called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required member variables.

<span class="mw-page-title-main">Dependency injection</span> Software programming technique

In software engineering, dependency injection is a design pattern in which an object or function receives other objects or functions that it depends on. Dependency injection aims to separate the concerns of constructing objects and using them, leading to loosely coupled programs. The pattern ensures that an object or function which wants to use a given service should not have to know how to construct those services. Instead, the receiving 'client' is provided with its dependencies by external code, which it is not aware of. Dependency injection helps by making implicit dependencies explicit and helps solve the following problems:

<span class="mw-page-title-main">Factory (object-oriented programming)</span> An object which creates other objects

In object-oriented programming, a factory is an object for creating other objects; formally, it is a function or method that returns objects of a varying prototype or class from some method call, which is assumed to be "new". More broadly, a subroutine that returns a "new" object may be referred to as a "factory", as in factory method or factory function. The factory pattern is the basis for a number of related software design patterns.

In programming languages, an abstract type is a type in a nominative type system that cannot be instantiated directly; a type that is not abstract – which can be instantiated – is called a concrete type. Every instance of an abstract type is an instance of some concrete subtype. Abstract types are also known as existential types.

In software engineering, a fluent interface is an object-oriented API whose design relies extensively on method chaining. Its goal is to increase code legibility by creating a domain-specific language (DSL). The term was coined in 2005 by Eric Evans and Martin Fowler.

<span class="mw-page-title-main">Vala (programming language)</span> Programming language

Vala is an object-oriented programming language with a self-hosting compiler that generates C code and uses the GObject system.

This article describes the syntax of the C# programming language. The features described are compatible with .NET Framework and Mono.

In object-oriented programming, "immutable interface" is a pattern for designing an immutable object. The immutable interface pattern involves defining a type which does not provide any methods which mutate state. Objects which are referenced by that type are not seen to have any mutable state, and appear immutable.

References

  1. 1 2 Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides (1994). Design Patterns: Elements of Reusable Object-Oriented Software . Addison Wesley. pp.  97ff. ISBN   0-201-63361-2.{{cite book}}: CS1 maint: multiple names: authors list (link)
  2. "The Builder design pattern - Problem, Solution, and Applicability". w3sDesign.com. Retrieved 2017-08-13.
  3. 1 2 "Index of /archive/2010/winter/51023-1/presentations" (PDF). www.classes.cs.uchicago.edu. Retrieved 2016-03-03.
  4. "The Builder design pattern - Structure and Collaboration". w3sDesign.com. Retrieved 2017-08-12.