Fluent Builder Pattern
Gamma Categorization: Creational Design PattenSummary: Extension of the Builder Pattern, that allows us to chain the operation calls.
Problem examples
We want to chain the operation calls for convenience purposes.Solution
The methods now return the class itself.Sample Code
Plese refer to the Builder Pattern article for the complete code.
The main changes are made in the base abstract class of the ReportBuilder.
The main changes are made in the base abstract class of the ReportBuilder.
public abstract class ReportBuilder
{
protected Report report;
public ReportBuilder CreateReport()
{
report = new Report();
return this;
}
public ReportBuilder SetHeader(string header)
{
report.Header = header;
return this;
}
public ReportBuilder AppendContentLine(string contentLine)
{
report.Content.Add(contentLine);
return this;
}
public ReportBuilder SetFooter(string footer)
{
report.Footer = footer;
return this;
}
public abstract string DispatchReport();
public void Clear() => report = new Report();
}
Usage
The usage is now simplified as follows.
var textReportBuilder = new TextReportBuilder();
var report = textReportBuilder.CreateReport()
.SetHeader($"Daily Report - {DateTime.UtcNow.ToString("dd/MM/yyyy")}")
.AppendContentLine("14 Hot Meals")
.AppendContentLine("22 Breakfasts")
.SetFooter("Copyright - Cafe Shop")
.DispatchReport();
System.Console.WriteLine(report);
Comments
Post a Comment