Implementing the Builder Design Pattern Using .NET and C#

Simplifying Object Construction with the Builder Design Pattern in C#

Abdelmajid BACO

--

Photo by Aedrian on Unsplash

The builder pattern is a design pattern that allows you to create complex objects by specifying their components step by step.

Here is an example of how you might use the Builder Pattern class:

// Builder interface
public interface IHtmlBuilder
{
void AddHeading(string heading);
void AddParagraph(string paragraph);
void AddLineBreak();
string Build();
}

// Concrete builder
public class HtmlBuilder : IHtmlBuilder
{
private readonly string _rootName;
private readonly HtmlElement _root = new HtmlElement();
public HtmlBuilder(string rootName)
{
_rootName = rootName;
_root.Name = rootName;
}

public void AddHeading(string heading)
{
var element = new HtmlElement {Name = "h1", Text = heading};
_root.Elements.Add(element);
}
public void AddParagraph(string paragraph)
{
var element = new HtmlElement {Name = "p", Text = paragraph};
_root.Elements.Add(element);
}
public void AddLineBreak()
{
var element = new HtmlElement {Name = "br"};
_root.Elements.Add(element);
}
public string Build()
{
return _root.ToString();
}
}

// Element
public class HtmlElement
{
public string Name, Text;
public List<HtmlElement> Elements = new List<HtmlElement>();
private const int _indentSize = 2;

public override string ToString()
{
var sb = new StringBuilder();
var i = new string(' ', _indentSize);
sb.Append($"{i}<{Name}>\n");
if (!string.IsNullOrWhiteSpace(Text))
{
sb.Append(new string(' ', _indentSize * 2));
sb.Append(Text);
sb.Append("\n");
}

foreach (var htmlElement in Elements)
{
sb.Append(htmlElement.ToString());
}

sb.Append($"{i}</{Name}>\n");
return sb.ToString();
}
}

// Client
class Program
{
static void Main(string[] args)
{
var htmlBuilder = new HtmlBuilder("html");
htmlBuilder.AddHeading("Hello World!");
htmlBuilder.AddParagraph("This is a simple HTML document.");
htmlBuilder.AddLineBreak();
htmlBuilder.AddParagraph("It…

--

--

Abdelmajid BACO

Senior Full Stack .Net / Angular Developer, Cloud & Azure DevOps, Carrier Manager, Husband, and Father.