Kihagyás

Builder design pattern

Builder

This pattern is used to construct complex classes step-by-step. This is commonly used when plenty of attributes and configuration is needed, but they barely depends on each other, or when the object can be in an unfinished state.

If you remember boby, the StringBuilder...

Example

Look at this pizza, I can't really just insert my fridge into the oven and pray for mercy, I have to prepare all the ingredients at once, and when everything is ready, bake into something less of a failure.

namespace Classes
{
    public class Pizza
    {
        string topping;
        string sauce;
        string dough;

        public Pizza(string topping, string sauce, string dough)
        {
            this.topping = topping;
            this.sauce = sauce;
            this.dough = dough;
        }
    }
}

Solution

The Builder will remember all the ingredients I prepared so far, but the order doesn't really matter

(it's time for ADHD to kick in and start with the sauce...)

using System;
using Classes;

namespace Design_Patterns.Patterns
{
    public class PizzaBuilder
    {
        string topping;
        string sauce;
        string dough;

        public PizzaBuilder()
        {
            topping = string.Empty;
            sauce = string.Empty;
            dough = string.Empty;
        }

        void addTopping(string topping)
        {
            this.topping += " " + topping;
        }
        void setDough(string dough)
        {
            this.dough = dough;
        }
        void addSauce(string sauce)
        {
            this.sauce += " " + sauce;
        }

        Pizza Bake()
        {
            return new Pizza(topping, sauce, dough);
        }
    }
}

Anyways, you can see where this is goin'. Not much of a big deal dough 😅