模式定义
动态(组合)地给一个对象增加一些额外的职责,就增加功能而言,Decorator模式比生成子类(继承)更为灵活(消除重复代码并且减少子类个数)
类图
应用场景
扩展一个类的功能或给一个类添加附加职责
优点
1.符合开闭原则
2.不改变原有对象的情况下给一个对象扩展功能
3.使用不同的组合可以实现不同的效果
要点总结
- 通过采用组合而非继承的手法,Decorator模式实现了在运行时动态扩展对象功能的能力,而且可以根据需要扩展多个功能。避免了使用继承带来的“灵活性差”和“多子类衍生问题”
- Decorator类在接口上表现为is-a 的继承关系,即Decorator类继承了Component类所具有的接口,但在实现上又表现为has-a的组合关系,即Decorator类又使用了另外一个Component类
- Decorator模式的目的并非解决“多子类衍生的多继承”问题,Decorator模式应用的要点在于解决“主体类在多个问题方向上的扩展功能”--是为“装饰”的含义
Go语言代码实现
工程目录
Decorator.go
package Decorator
import "fmt"
//定义一个抽象组件
type Component interface {
Operate()
}
//实现一个具体的组件:组件1
type Compontent1 struct {
}
func (c1 *Compontent1) Operate() {
fmt.Println("c1 operate")
}
//定义一个抽象的装饰者
type Decorator interface {
Component
Do() //这是一个额外的方法
}
//实现一个具体的装饰者
type Decorator1 struct {
c Component
}
func (d1 *Decorator1) Do() {
fmt.Println("发生了装饰行为")
}
func (d1 *Decorator1) Operate() {
d1.Do()
d1.c.Operate()
}
Decorator_test.go
package Decorator
import "testing"
func TestCompontent1_Operate(t *testing.T) {
c1 := &Compontent1{}
c1.Operate()
}
func TestDecorator1_Operate(t *testing.T) {
d1 := &Decorator1{}
c1 := &Compontent1{}
d1.c = c1
d1.Operate()
}