Skip to content

Instantly share code, notes, and snippets.

@morristech
Forked from amirraza/User - HtmlCodeGenerator.kt
Created September 18, 2021 15:14
Show Gist options
  • Select an option

  • Save morristech/cab479e39a58fd2c8865d82d5cb2385e to your computer and use it in GitHub Desktop.

Select an option

Save morristech/cab479e39a58fd2c8865d82d5cb2385e to your computer and use it in GitHub Desktop.
Composite Design Pattern to generate html code
fun main() {
val html = HtmlParentElement("<html>", "</html>")
val head = HtmlParentElement("<head>", "</head>")
val body = HtmlParentElement("<body>", "</body>")
val title = HtmlElement("<title>", "</title>", "Auto Generated Html title")
head.addElement(title)
val firstHeding = HtmlElement("<h1>", "</h1>", "this is first heading")
val firstPara = HtmlElement("<p>", "</p>", "this is first paragraph")
val firstdiv = HtmlParentElement("<div>", "</div>")
val firstParaInsideDiv = HtmlElement("<p>", "</p>", "this is first paragraph inside Div")
val secondDiv = HtmlParentElement("<div>", "</div>", "This is a second div")
val paraInsideSecondDiv = HtmlElement("<p>", "</p>", "this is first paragraph inside second div")
secondDiv.addElement(paraInsideSecondDiv)
firstdiv.addElement(firstParaInsideDiv)
firstdiv.addElement(secondDiv)
body.addElement(firstHeding)
body.addElement(firstPara)
body.addElement(firstdiv)
html.addElement(head)
html.addElement(body)
//As `html` is a Composite object, the generateHtmlCode() method will call
//recursively composite objects until the Leaf object found.
html.generateHtmlCode()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment