Builder Pattern
Builder Pattern comes under creation type design pattern. It helps in separating the construction of a complex object by using step by step approach. In this, Director controls the creation process, and Builder is independent of the creation process.
The following items are elements of the builder pattern,
- Builder - It specifies an abstract interface for creating parts of a product object.
- ConcreteBuilder - It creates and assembles parts of the product by implanting The Builder Interface. It also provides an interface for retrieving the product.
- Director - It constructs an object using Builder Interface. It actually acts as an overall master object that takes care of the builder creation and setup, and makes sure it has the 'ConcreteBuilders' it requires.
- Product - The target object produced by the builder.
To understand the above point, let us take an example of laptop manufacturing system. Let's assume that we have a system installed at one of the laptop vendors. Now, the manufacturer may decide to create a laptop based on parameters like Touchscreen, Operating System, Battery and Stylus. If we have the objects for all these parts, then creation of product with any combination of above parts would lead to a very complex and unmanageable code in the client application i.e. the module that will decide what kind of laptop needs to be built.
Below is implementation,
- public enum ScreenType {
- ScreenType_TOUCH_CAPACITIVE,
- ScreenType_NON_TOUCH
- };
- public enum Battery {
- MAH_25000,
- MAH_15000,
- MAH_20000
- };
- public enum OperatingSystem {
- ANDROID,
- WINDOWS,
- SYMBIAN
- };
- public enum Stylus {
- YES,
- NO
- };
Above are some helper enums to identify various parts.
Product
- class Laptop {
- // fields to hold the part type
- string laptopName;
- ScreenType laptopScreen;
- Battery laptopBattery;
- OperatingSystem laptopOS;
- Stylus laptopStylus;
- public Laptop(string name) {
- laptopName = name;
- }
- // Public properties to access laptop parts
- public string LaptopName {
- get {
- return laptopName;
- }
- }
- public ScreenType LaptopScreen {
- get {
- return laptopScreen;
- }
- set {
- laptopScreen = value;
- }
- }
- public Battery LaptopBattery {
- get {
- return laptopBattery;
- }
- set {
- laptopBattery = value;
- }
- }
- public OperatingSystem LaptopOS {
- get {
- return laptopOS;
- }
- set {
- laptopOS = value;
- }
- }
- public Stylus LaptopStylus {
- get {
- return laptopStylus;
- }
- set {
- laptopStylus = value;
- }
- }
- // Methiod to display laptop details in our own representation
- public override string ToString() {
- return string.Format("Name: {0}\nScreen: {1}\nBattery {2}\nOS: {3}\nStylus: {4}", LaptopName, LaptopScreen, LaptopBattery, LaptopOS, LaptopStylus);
- }
- }
Shown above is example of Product class which is created for assembling the parts of Laptop.

Join the conversation! Your thoughts help the community grow.