fork download
  1.  
  2.  
  3. public class Main {
  4.  
  5. public static void main(String args[]) {
  6. Page page = new Page();
  7. writeBody(page);
  8. page.show();
  9.  
  10. }
  11.  
  12. static void writeBody(Page page) {
  13. try (BodyTag bodyTag = new BodyTag(page)) {
  14. writeText(page);
  15. writeList(page);
  16. }
  17. }
  18.  
  19. static void writeText(Page page) {
  20. try (StrongTag strongTag = new StrongTag(page)) {
  21. strongTag.append(" some text ");
  22. }
  23. }
  24.  
  25. static void writeList(Page page) {
  26. try (ListTag list = new ListTag(page)) {
  27. // A twisted way to write a, b and c as elements
  28. for (char c=97; c<100; ++c) {
  29. appendElem(page, String.valueOf(c));
  30. }
  31. }
  32. }
  33.  
  34. static void appendElem(Page page, String elem) {
  35. try (ListElem li = new ListElem(page)) {
  36. li.append(elem);
  37. }
  38. }
  39. }
  40.  
  41. class Page {
  42.  
  43. StringBuilder content = new StringBuilder();
  44.  
  45. void append(String text) {
  46. content.append(text);
  47. }
  48.  
  49. void show() {
  50. System.out.println(content);
  51. }
  52. }
  53.  
  54. abstract class Tag implements AutoCloseable {
  55.  
  56. String name;
  57. Page content;
  58.  
  59. Tag(Page parent, String tagName) {
  60. name = tagName;
  61. content = parent;
  62. content.append("<");
  63. content.append(name);
  64. content.append(">");
  65. }
  66.  
  67. public void append(String text) {
  68. content.append(text);
  69. }
  70.  
  71. @Override
  72. final public void close() {
  73. content.append("</");
  74. content.append(name);
  75. content.append(">");
  76. }
  77. }
  78.  
  79. final class StrongTag extends Tag {
  80.  
  81. public StrongTag(Page parent) {
  82. super(parent, "strong");
  83. }
  84. }
  85.  
  86. final class BodyTag extends Tag {
  87.  
  88. public BodyTag(Page parent) {
  89. super(parent, "body");
  90. }
  91. }
  92.  
  93. final class ListTag extends Tag {
  94.  
  95. public ListTag(Page parent) {
  96. super(parent, "ol");
  97. }
  98. }
  99.  
  100. final class ListElem extends Tag {
  101.  
  102. public ListElem(Page parent) {
  103. super(parent, "li");
  104. }
  105. }
  106.  
Success #stdin #stdout 0.07s 380224KB
stdin
Standard input is empty
stdout
<body><strong> some text </strong><ol><li>a</li><li>b</li><li>c</li></ol></body>