装饰器模式
装饰器模式(Decorator pattern) 允许像一个现有对象添加新的功能, 同时又不会改变结构.
有点 和 缺点
优点:
- 装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能。
- 装饰器模式完全遵守开闭原则.
缺点:
- 装饰模式会增加许多子类,过度使用会增加程序得复杂性。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| type Shape interface { Draw() }
type Circle struct{ radius float64 }
func (c Circle) Draw() { fmt.Println("Draw circle:", c.radius) }
type Rectangle struct{ length float64 width float64 }
func (r Rectangle) Draw() { fmt.Println("Draw a rectangle") }
type ShapeDecorator interface { Shape }
type RedShapeDecorator struct { S Shape }
func (d RedShapeDecorator) Draw() { d.S.Draw() d.setRedBorder() }
func (d RedShapeDecorator) setRedBorder() { fmt.Println("Decorator:set red border") }
|