Skip to content

Creational Design Patterns

Creational Design Patterns provide various object creation mechanisms, which increase flexibility and reuse of existing code.

1. Builder

Builder is a creational design pattern that lets you construct complex objects step by step. The pattern allows you to produce different types and representations of an object using the same construction code.

HTMLComponent

Represents a component of HTML code.

Source code in src/creational/builder.py
class HTMLComponent:
    """Represents a component of HTML code."""

    def __init__(self, content: str):
        """
        Initializes an HTMLComponent.

        Args:
            content (str): The content of the HTML component.
        """
        self.content = content

    def render(self) -> str:
        """
        Renders the HTML component.

        Returns:
            str: The HTML code representation of the component.
        """
        return f"<div>{self.content}</div>"

__init__(content)

Initializes an HTMLComponent.

Parameters:

Name Type Description Default
content str

The content of the HTML component.

required
Source code in src/creational/builder.py
def __init__(self, content: str):
    """
    Initializes an HTMLComponent.

    Args:
        content (str): The content of the HTML component.
    """
    self.content = content

render()

Renders the HTML component.

Returns:

Name Type Description
str str

The HTML code representation of the component.

Source code in src/creational/builder.py
def render(self) -> str:
    """
    Renders the HTML component.

    Returns:
        str: The HTML code representation of the component.
    """
    return f"<div>{self.content}</div>"

CSSComponent

Represents a component of CSS code.

Source code in src/creational/builder.py
class CSSComponent:
    """Represents a component of CSS code."""

    def __init__(self, style: str):
        """
        Initializes a CSSComponent.

        Args:
            style (str): The CSS style of the component.
        """
        self.style = style

    def render(self) -> str:
        """
        Renders the CSS component.

        Returns:
            str: The CSS code representation of the component.
        """
        return f".element {{ {self.style} }}"

__init__(style)

Initializes a CSSComponent.

Parameters:

Name Type Description Default
style str

The CSS style of the component.

required
Source code in src/creational/builder.py
def __init__(self, style: str):
    """
    Initializes a CSSComponent.

    Args:
        style (str): The CSS style of the component.
    """
    self.style = style

render()

Renders the CSS component.

Returns:

Name Type Description
str str

The CSS code representation of the component.

Source code in src/creational/builder.py
def render(self) -> str:
    """
    Renders the CSS component.

    Returns:
        str: The CSS code representation of the component.
    """
    return f".element {{ {self.style} }}"

CodeBuilder

Builds HTML and CSS code by assembling components.

Source code in src/creational/builder.py
class CodeBuilder:
    """Builds HTML and CSS code by assembling components."""

    def __init__(self):
        """Initializes a CodeBuilder."""
        self.html_components = []
        self.css_components = []

    def add_html(self, content: str) -> 'CodeBuilder':
        """
        Adds an HTML component to the builder.

        Args:
            content (str): The content of the HTML component.

        Returns:
            CodeBuilder: The updated CodeBuilder instance.
        """
        self.html_components.append(HTMLComponent(content))
        return self

    def add_css(self, style: str) -> 'CodeBuilder':
        """
        Adds a CSS component to the builder.

        Args:
            style (str): The CSS style of the component.

        Returns:
            CodeBuilder: The updated CodeBuilder instance.
        """
        self.css_components.append(CSSComponent(style))
        return self

    def build_html(self) -> str:
        """
        Builds the HTML code from added HTML components.

        Returns:
            str: The generated HTML code.
        """
        return "\n".join(component.render() for component in self.html_components)

    def build_css(self) -> str:
        """
        Builds the CSS code from added CSS components.

        Returns:
            str: The generated CSS code.
        """
        return "\n".join(component.render() for component in self.css_components)

__init__()

Initializes a CodeBuilder.

Source code in src/creational/builder.py
def __init__(self):
    """Initializes a CodeBuilder."""
    self.html_components = []
    self.css_components = []

add_html(content)

Adds an HTML component to the builder.

Parameters:

Name Type Description Default
content str

The content of the HTML component.

required

Returns:

Name Type Description
CodeBuilder CodeBuilder

The updated CodeBuilder instance.

Source code in src/creational/builder.py
def add_html(self, content: str) -> 'CodeBuilder':
    """
    Adds an HTML component to the builder.

    Args:
        content (str): The content of the HTML component.

    Returns:
        CodeBuilder: The updated CodeBuilder instance.
    """
    self.html_components.append(HTMLComponent(content))
    return self

add_css(style)

Adds a CSS component to the builder.

Parameters:

Name Type Description Default
style str

The CSS style of the component.

required

Returns:

Name Type Description
CodeBuilder CodeBuilder

The updated CodeBuilder instance.

Source code in src/creational/builder.py
def add_css(self, style: str) -> 'CodeBuilder':
    """
    Adds a CSS component to the builder.

    Args:
        style (str): The CSS style of the component.

    Returns:
        CodeBuilder: The updated CodeBuilder instance.
    """
    self.css_components.append(CSSComponent(style))
    return self

build_html()

Builds the HTML code from added HTML components.

Returns:

Name Type Description
str str

The generated HTML code.

Source code in src/creational/builder.py
def build_html(self) -> str:
    """
    Builds the HTML code from added HTML components.

    Returns:
        str: The generated HTML code.
    """
    return "\n".join(component.render() for component in self.html_components)

build_css()

Builds the CSS code from added CSS components.

Returns:

Name Type Description
str str

The generated CSS code.

Source code in src/creational/builder.py
def build_css(self) -> str:
    """
    Builds the CSS code from added CSS components.

    Returns:
        str: The generated CSS code.
    """
    return "\n".join(component.render() for component in self.css_components)

main()

Steps to implement:

1. Create Code Builder's Instance

2. Add HTML and CSS code

3. Finally build the HTML & CSS code using Code Builder's Instance

Source code in src/creational/builder.py
def main():
    """
    **Steps to implement:**\n
    **1. Create Code Builder's Instance**\n
    **2. Add HTML and CSS code**\n
    **3. Finally build the HTML & CSS code using Code Builder's Instance**\n
    """
    builder = CodeBuilder()
    builder.add_html("Hello, world!")
    builder.add_css("color: blue;")
    html_code = builder.build_html()
    css_code = builder.build_css()

    print("Generated HTML:")
    print(html_code)
    print("\nGenerated CSS:")
    print(css_code)

Source Code

src/creational/builder.py
class HTMLComponent:
    def __init__(self, content: str):
        self.content = content

    def render(self) -> str:
        return f"<div>{self.content}</div>"


class CSSComponent:
    def __init__(self, style: str):
        self.style = style

    def render(self) -> str:
        return f".element {{ {self.style} }}"


class CodeBuilder:
    def __init__(self):
        self.html_components = []
        self.css_components = []

    def add_html(self, content: str) -> 'CodeBuilder':
        self.html_components.append(HTMLComponent(content))
        return self

    def add_css(self, style: str) -> 'CodeBuilder':
        self.css_components.append(CSSComponent(style))
        return self

    def build_html(self) -> str:
        return "\n".join(component.render() for component in self.html_components)

    def build_css(self) -> str:
        return "\n".join(component.render() for component in self.css_components)


def main():
    builder = CodeBuilder()
    builder.add_html("Hello, world!")
    builder.add_css("color: blue;")
    html_code = builder.build_html()
    css_code = builder.build_css()

    print("Generated HTML:")
    print(html_code)
    print("\nGenerated CSS:")
    print(css_code)


if __name__ == "__main__":
    main()

Another Example

src/creational/builder_example.py
from typing import List, Union


# Product classes
class Button:
    """A class representing a button UI component."""

    def __init__(self, text: str):
        """Initialize the Button with text."""
        self.text = text

    def display(self) -> None:
        """Display the button."""
        print(f"Button: {self.text}")


class TextField:
    """A class representing a text field UI component."""

    def __init__(self, label: str):
        """Initialize the TextField with a label."""
        self.label = label

    def display(self) -> None:
        """Display the text field."""
        print(f"Text Field: {self.label}")


class Checkbox:
    """A class representing a checkbox UI component."""

    def __init__(self, label: str):
        """Initialize the Checkbox with a label."""
        self.label = label

    def display(self) -> None:
        """Display the checkbox."""
        print(f"Checkbox: {self.label}")


# Builder interface
class DesignTool:
    """An interface for building UI components."""

    def create_button(self, text: str) -> None:
        """Create a button UI component."""
        pass

    def create_text_field(self, label: str) -> None:
        """Create a text field UI component."""
        pass

    def create_checkbox(self, label: str) -> None:
        """Create a checkbox UI component."""
        pass


# Concrete builder
class Figma(DesignTool):
    """A concrete builder for building simple UI components."""

    def __init__(self):
        """Initialize Figma."""
        self.components: List[Union[Button, TextField, Checkbox]] = []

    def create_button(self, text: str) -> None:
        """Create a button UI component."""
        self.components.append(Button(text))

    def create_text_field(self, label: str) -> None:
        """Create a text field UI component."""
        self.components.append(TextField(label))

    def create_checkbox(self, label: str) -> None:
        """Create a checkbox UI component."""
        self.components.append(Checkbox(label))

    def render_design(self) -> List[Union[Button, TextField, Checkbox]]:
        """Get the result of the design process."""
        return self.components


# Director
class Designer:
    """A class responsible for managing the construction process."""

    def __init__(self, designTool: DesignTool):
        """Initialize the Designer with a designTool."""
        self.designTool = designTool

    def build_basic_ui(self) -> None:
        """Build a basic UI."""
        self.designTool.create_button("Submit")
        self.designTool.create_text_field("Username")
        self.designTool.create_text_field("Password")
        self.designTool.create_checkbox("Remember me")


def main() -> None:
    """
    **Steps to implement:**
    **1. Instantiate Figma**
    **2. Instantiate Designer with the figma**
    **3. Designer builds a basic UI**
    **4. Get the constructed UI components**
    **5. Display the created UI components**
    """
    figma = Figma()
    designer = Designer(figma)
    designer.build_basic_ui()
    ui_components = figma.render_design()

    print("Created UI Components:")
    for component in ui_components:
        component.display()


if __name__ == "__main__":
    main()

Class Diagram

classDiagram
    class Button {
        display()
    }
    class TextField {
        display()
    }
    class Checkbox {
        display()
    }
    class DesignTool {
        create_button()
        create_text_field()
        create_checkbox()
    }
    class Figma {
        create_button()
        create_text_field()
        create_checkbox()
        render_design()
    }
    class Designer {
        build_basic_ui()
    }
    class UI {
        TextField
        Checkbox
        Button
    }
    Button <|-- Figma
    TextField <|-- Figma
    Checkbox <|-- Figma
    DesignTool --|> Figma
    DesignTool <|-- Designer
    Button --|> UI
    TextField --|> UI 
    Checkbox --|> UI