Pattern: Builder
The intent of the Builder design pattern is to separate the construction of a complex object from its representation.
Purpose of .NET implementation
You want to let the developer construct a SqlConnectionString.
The SqlConnectionStringBuilder class provides a way to construct connection strings for SQL Server databases.
Instead of requiring the developer to construct a connection string in one go, potentially leading to mistakes or omissions, SqlConnectionStringBuilder allows for the step-by-step construction of a connection string.
This can help to ensure that all necessary parameters are included and that the connection string is correctly formatted.
Once all necessary parameters have been set, the ConnectionString property of the SqlConnectionStringBuilder object can be used to retrieve the constructed connection string.
Examples in .NET :
SqlConnectionStringBuilder
namespace Builder;
internal class ConnectionStringDemo
{
public static void ConnectionString()
{
//start example 2
SqlConnectionStringBuilder build = new ();
build.DataSource = ".";
build.InitialCatalog = "MyDatabase";
build.ConnectTimeout = 30;
// Outputs the constructed connection string to the console. This demonstrates the final product of the Builder pattern.
Console.WriteLine(build.ConnectionString);
//end example 2
}
}
UriBuilder
namespace Builder;
static class UriBuilderDemo
{
public static void UriMod()
{
//start example 1
var uri = new Uri("https://msprogrammer.serviciipeweb.ro/category/friday-links/");
var b = new UriBuilder(uri);
//changing part
b.Scheme = "http";
//now we have http://msprogrammer.serviciipeweb.ro/category/friday-links/
Console.WriteLine(b.Uri);
//changing part
b.Path = "2018/03/05/design-patterns-class/";
//now we have http://msprogrammer.serviciipeweb.ro/2018/03/05/design-patterns-class/
Console.WriteLine(b.Uri);
//end example 1
}
}
See Source Code for Microsoft implementation of Builder
SourceCode SqlConnectionStringBuilderSourceCode UriBuilder
Learn More
C2Wikidofactory
DPH
Wikipedia
Homework
Imagine that you have a logger that logs to a file and to a console.
Implement a builder that will allow you to create a logger with different configurations.
For example, you can set the log level, the log format, and the log destination.