Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- "template"
- "bytes"
- )
- // Element
- type IElement interface {
- Name() string
- Value() string
- }
- type Element struct {
- name string
- value string
- Decorators []IDecorator
- }
- func (this *Element) Init(name string) {
- this.name = name
- this.AddDecorator(&TemplateDecorator{ Element : this })
- this.AddDecorator(&TagDecorator{ Element : this })
- }
- func (this *Element) AddDecorator(decorator IDecorator) {
- this.Decorators = append(this.Decorators, decorator)
- }
- func (this *Element) Name() string {
- return this.name
- }
- func (this *Element) Value() string {
- return this.value
- }
- func (this *Element) SetValue(value string) {
- this.value = value
- }
- func (this *Element) Template() string {
- return "**{Element.Value}**"
- }
- func (this *Element) String() string {
- content := ""
- for _, decorator := range this.Decorators {
- content = decorator.Decorate(content)
- }
- return content
- }
- // TextElement
- type TextElement struct {
- Element
- }
- func (this *TextElement) Template() string {
- return "##{Element.Value}##"
- }
- // Decorators
- type IDecorator interface {
- Decorate(content string) string
- }
- // Tag Decorator
- type TagDecorator struct {
- Element IElement
- }
- func (this *TagDecorator) Decorate(content string) string {
- return fmt.Sprintf("<%s>%s</%s>", this.Element.Name(), content, this.Element.Name())
- }
- // Template Decorator
- type ITplElement interface {
- IElement
- Template() string
- }
- type TemplateDecorator struct {
- Element ITplElement
- }
- func (this *TemplateDecorator) Decorate(content string) string {
- tpl := template.MustParse(this.Element.Template(), nil)
- w := bytes.NewBuffer(nil)
- if err := tpl.Execute(w, this); err != nil {
- return content
- }
- return w.String()
- }
- func main() {
- el := &TextElement{}
- el.Init("myname")
- el.SetValue("Valueable")
- fmt.Println(el.String())
- }
- #### OUTPUT ####
- <myname>**Valueable**</myname>
- #### INTENDED ####
- <myname>##Valueable##</myname>
Add Comment
Please, Sign In to add comment