Design Pattern for generating HTML Tags

design-patterns, html, java

Solution

On first glance I thought of a Builder pattern or better a fluent API. A bit more compact is the following:

import static a.b.c.HTML.*;

    String html = p(
                ol(
                    li(),
                    li(
                        _("Hello, "),
                        strong(_("World")),
                        _("!")
                    ),
                    li()
                )
            ).toString();


public class HTML {

    protected final String tag;
    private final HTML[] items;

    public HTML(String tag, final HTML... items) {
        this.tag = tag;
        this.items = items;
    }

    public static HTML _(String text) {
        return new HTML(text) {

            @Override
            public String toString() {
                return tag;
            }

            @Override
            protected void buildString(StringBuilder sb) {
                sb.append(tag);
            }
       };
    }

    public static HTML li(final HTML... items) {
        return new HTML("li", items);
    }

    public static HTML ol(final HTML... items) {
        return new HTML("ol", items);
    }

    public static HTML p(final HTML... items) {
        return new HTML("p", items);
    }

    public static HTML strong(final HTML... items) {
        return new HTML("strong", items);
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        buildString(sb);
        return sb.toString();
    }

    protected void buildString(StringBuilder sb) {
        sb.append('<').append(tag);
        if (items.length == 0) {
            sb.append(" />"); 
        } else {
            sb.append('>');
            for (HTML item : items) {
                item.buildString(sb);
            }
            sb.append("</").append(tag).append('>');
        }

    }
}

Problem

For a small system that can get a String and output an HTML, what design pattern would be suitable? This is a small example: ``` public String makeStrong(String in) { return "<strong>" + in + "</strong>"; } ``` Of course it needs to model some hierarchical structure so that it can fit `<ul>` and `<ol>` and their children. I'm thinking of Decorator but Composite pattern sounds good too. What should I consider?

Original source