Guest User

Untitled

a guest
Oct 17th, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "template"
  6. "bytes"
  7. )
  8.  
  9. // Element
  10. type IElement interface {
  11. Name() string
  12. Value() string
  13. }
  14.  
  15. type Element struct {
  16. name string
  17. value string
  18.  
  19. Decorators []IDecorator
  20. }
  21.  
  22. func (this *Element) Init(name string) {
  23. this.name = name
  24.  
  25. this.AddDecorator(&TemplateDecorator{ Element : this })
  26. this.AddDecorator(&TagDecorator{ Element : this })
  27. }
  28.  
  29. func (this *Element) AddDecorator(decorator IDecorator) {
  30. this.Decorators = append(this.Decorators, decorator)
  31. }
  32.  
  33. func (this *Element) Name() string {
  34. return this.name
  35. }
  36.  
  37. func (this *Element) Value() string {
  38. return this.value
  39. }
  40.  
  41. func (this *Element) SetValue(value string) {
  42. this.value = value
  43. }
  44.  
  45. func (this *Element) Template() string {
  46. return "**{Element.Value}**"
  47. }
  48.  
  49. func (this *Element) String() string {
  50. content := ""
  51. for _, decorator := range this.Decorators {
  52. content = decorator.Decorate(content)
  53. }
  54. return content
  55. }
  56.  
  57. // TextElement
  58. type TextElement struct {
  59. Element
  60. }
  61.  
  62. func (this *TextElement) Template() string {
  63. return "##{Element.Value}##"
  64. }
  65.  
  66.  
  67. // Decorators
  68. type IDecorator interface {
  69. Decorate(content string) string
  70. }
  71.  
  72. // Tag Decorator
  73. type TagDecorator struct {
  74. Element IElement
  75. }
  76.  
  77. func (this *TagDecorator) Decorate(content string) string {
  78. return fmt.Sprintf("<%s>%s</%s>", this.Element.Name(), content, this.Element.Name())
  79. }
  80.  
  81. // Template Decorator
  82. type ITplElement interface {
  83. IElement
  84. Template() string
  85. }
  86.  
  87. type TemplateDecorator struct {
  88. Element ITplElement
  89. }
  90.  
  91. func (this *TemplateDecorator) Decorate(content string) string {
  92. tpl := template.MustParse(this.Element.Template(), nil)
  93.  
  94. w := bytes.NewBuffer(nil)
  95. if err := tpl.Execute(w, this); err != nil {
  96. return content
  97. }
  98. return w.String()
  99. }
  100.  
  101. func main() {
  102. el := &TextElement{}
  103. el.Init("myname")
  104. el.SetValue("Valueable")
  105.  
  106. fmt.Println(el.String())
  107. }
  108.  
  109. #### OUTPUT ####
  110.  
  111. <myname>**Valueable**</myname>
  112.  
  113. #### INTENDED ####
  114.  
  115. <myname>##Valueable##</myname>
Add Comment
Please, Sign In to add comment