dimanche 1 septembre 2019

use Builder pattern combined with protected access modifier

I'm reading a book in Design Patterns, and below is some code example used by the author. The author tries to build a html builder as:

public class HtmlElement
{
    public string Name, Text;
    public List<HtmlElement> Elements = new List<HtmlElement>();

    public HtmlElement() { }
    public HtmlElement(string name, string text)
    {
        Name = name;
        Text = text;
    }
}

//builder class
public class HtmlBuilder
{
    protected readonly string rootName;
    protected HtmlElement root = new HtmlElement();
    public HtmlBuilder(string rootName)
    {
        this.rootName = rootName;
        root.Name = rootName;
    }
    public HtmlBuilder AddChild(string childName, string childText)
    {
        var e = new HtmlElement(childName, childText);
        root.Elements.Add(e);
        return this;            //fluent api
    }

     // to return a HtmlElement object
    public static implicit operator HtmlElement(HtmlBuilder builder)
    {
        return builder.root;
    }
    public override string ToString() => root.ToString();
}

then the author says:

"To simply force users to use the Builder whenever they are constructing a HtmlElement object, we have hidden all constructors of HtmlElement class as":

public class HtmlElement
{
   ...
   protected HtmlElement() { }
   protected HtmlElement(string name, string text)
   {
      Name = name;
      Text = text;
   }
   ...
}

so users can go like

HtmlElement root = HtmlElement.Create("ul").AddChildFluent("li", "hello").AddChildFluent("li", "world");

Console.WriteLine(root);

here is what I don't understand, the author changed the constructors of HtmlElement to protected, which means that HtmlBuilder class cannot access to the protected constructors like

protected HtmlElement root = new HtmlElement();    // not allowed

so does it mean that we need to let the HtmlBuilder inherit from HtmlElement? But they are no inheritance context at all, so how can I modify it?

Aucun commentaire:

Enregistrer un commentaire