Scan with Phone

Scan to instantly open and share this page on your mobile device.

Link copied to clipboard!

Factory Method

Defer product choice to subclasses.

C#

abstract class ReportCreator
{
    public string Build() => Create().Render(); // invariant algorithm
    protected abstract IReport Create(); // factory method
}
interface IReport
{
    string Render();
}
class PdfReport : IReport
{
    public string Render() => "PDF";
}
class HtmlReport : IReport
{
    public string Render() => "HTML";
}
class PdfCreator : ReportCreator
{
    protected override IReport Create() => new PdfReport();
}
class HtmlCreator : ReportCreator
{
    protected override IReport Create() => new HtmlReport();
}
string out1 = new PdfCreator().Build(); // PDF
string out2 = new HtmlCreator().Build(); // HTML
next