Dynamic object behavior change or add decorative patterns using object combinations of ways.
Anonymous combination of non-invasive interfaces and can be easily achieved by means of decorative patterns Go language.
Use anonymous combination, in decorator not need to explicitly define the transpose method of the original object.
Decorator Package Import ( _ "FMT" ) type interface BaseCal { Cal () int } // Examples of computer type Computer struct { // what function nor } FUNC (the this * Computer) Cal () {int return 0 } FUNC NewComputer ( ) BaseCal { return & Computer {} } type struct {addDecorator BaseCal NUM int } FUNC (the this addDecorator *) Cal () {int return this.BaseCal.Cal () + this.num } // add a function to add Computer func NewAdd (CoMP BaseCal, NUM int) BaseCal { return {& addDecorator BaseCal: CoMP, NUM: NUM, } } struct {MulDecorator type BaseCal NUM int } // Add to a * Computer function FUNC (the this MulDecorator *) Cal () {int return this.BaseCal.Cal () * this.num } FUNC NewMul (CoMP BaseCal, NUM int) BaseCal { return {& MulDecorator BaseCal: CoMP, NUM: NUM, } }
c := decorator.NewComputer() c = decorator.NewAdd(c,10) c = decorator.NewMul(c,9) fmt.Println(c.Cal())//输出:90