Design Patterns

Builder Design Pattern

Builder pattern separate the construction of a object from its representation so that the same construction process can create different representations.

The Builder Pattern is comprised of four components: a builder interface, a concrete builder, a director and a product.

Builder is an interface which is used to define all the steps to create a product.

   //This is the Builder Interface  
public interface IBlogBuilder
{
void BuildSendEmail();
void BuildShare();
Blog blog { get; }
}

ConcreteBuilder is a class which implements the Builder interface to create complex product.

 //This is the Post Concrete Builder class  
public class PostBuilder : IBlogBuilder
{
Blog post;
public PostBuilder()
{
post = new Blog("New Post 1");
}
public void BuildSendEmail()
{
post.SendEmail();
}
public void BuildShare()
{
post.Share();
}
}
//This is the Page Concrete Builder class
public class PageBuilder : IBlogBuilder
{
Blog page;
public PageBuilder()
{
page = new Blog("New Page 1");
}
public void BuildSendEmail()
{
page.SendEmail();
}
public void BuildShare()
{
page.Share();
}
}

Product is a class which defines the parts of the complex object which are to be generated by the builder pattern.

 //This is the Product  
public class Blog
{
string Title;
public Blog(string name)
{
Title = name;
}
public void SendEmail()
{
//TO DO : Send Email Logic
}
public void Share()
{
//TO DO : Send Share Logic
}
}

Director is a class which is used to construct an object using the Builder interface.

 //This is the Director class  
public class BuildBlog
{
public void ConstructBlog(IBlogBuilder blogBuilder)
{
blogBuilder.BuildSendEmail();
blogBuilder.BuildShare();
}
}

Now when we look at the client code we can see how clean it is to create any product.

 using System;  
namespace dotnetfundamentals.BuilderPattern
{
class Program
{
static void Main(string[] args)
{
//This will create instance of Director
BuildBlog newPost = new BuildBlog();

//Initializes Builder class
IBlogBuilder blogBuilder = null;

//This will create New Post
blogBuilder = new PostBuilder();
newPost.ConstructBlog(blogBuilder);

//This will create New Page
blogBuilder = new PageBuilder();
newPost.ConstructBlog(blogBuilder);
}
}
}

Leave a comment