闲聊设计模式 | 装饰者模式
目录
本文介绍在 go 语言中使用装饰者模式.
一、前言
Decorator Pattern(装饰模式)
维基百科
This pattern creates a decorator class which wraps the original class and provides additional functionality keeping class methods signature intact.
白话文:
这个模式我们需要创建一个新的装饰类,然后装饰类会拥有一个属性是被装饰类,并且会有“一个”方法和需要使用的被装饰类的方法签名完全一致,调用装饰类的方法会执行装饰类内容并调用被装饰类的被装饰方法.
故事:
我买了一本书《go编程思想》,小明也买了一本书《go编程思想》并给它带上了一个黄金封面,两本书内容一摸一样,只是小明的变成金灿灿的土豪版.
二、实例
2.1 对于某个接口的方法装饰
代码:
1package decorator
2
3import (
4 "fmt"
5 "testing"
6)
7
8type Shape interface {
9 draw()
10}
11
12type Circle struct {
13}
14
15func (shape Circle) draw() {
16 fmt.Println("Shape: Circle")
17}
18
19type Rectangle struct {
20}
21
22func (shape Rectangle) draw() {
23 fmt.Println("Shape: Rectangle")
24}
25
26type ShapeDecorator struct {
27 decoratorShape Shape
28}
29
30func (shape ShapeDecorator) draw() {
31 shape.decoratorShape.draw()
32}
33
34type RedShapeDecorator struct {
35 ShapeDecorator
36}
37
38func NewRedShapeDecorator(s Shape) *RedShapeDecorator {
39 d := new(RedShapeDecorator)
40 d.decoratorShape = s
41 return d
42}
43
44func (shape RedShapeDecorator) draw() {
45 shape.ShapeDecorator.draw()
46 fmt.Println("red")
47}
48
49type BlueShapeDecorator struct {
50 ShapeDecorator
51}
52
53func NewBlueShapeDecorator(s Shape) *BlueShapeDecorator {
54 d := new(BlueShapeDecorator)
55 d.decoratorShape = s
56 return d
57}
58
59func (shape BlueShapeDecorator) draw() {
60 shape.ShapeDecorator.draw()
61 fmt.Println("blue")
62}
63
64func TestName(t *testing.T) {
65 redShapedDecorator := NewRedShapeDecorator(Circle{})
66 redShapedDecorator.draw()
67
68 redShapedDecorator = NewRedShapeDecorator(Rectangle{})
69 redShapedDecorator.draw()
70
71 blueShapedDecorator := NewBlueShapeDecorator(Circle{})
72 blueShapedDecorator.draw()
73
74 blueShapedDecorator = NewBlueShapeDecorator(Rectangle{})
75 blueShapedDecorator.draw()
76}
输出结果:
1Shape: Circle
2red
3Shape: Rectangle
4red
5Shape: Circle
6blue
7Shape: Rectangle
8blue
2.2 直接装饰方法
代码:
1type drawFunc func()
2
3func CircleDraw() {
4 fmt.Println("Shape: Circle")
5}
6
7func RedCircleDraw(d drawFunc) drawFunc {
8 return func() {
9 d()
10 fmt.Println("red")
11 }
12}
13
14func TestFunc(t *testing.T) {
15 var drawFunc drawFunc
16 drawFunc = CircleDraw
17 drawFunc()
18
19 drawFunc = RedCircleDraw(drawFunc)
20 drawFunc()
21}
输出结果:
1Shape: Circle
2Shape: Circle
3red
三、参考
https://www.tutorialspoint.com/design_pattern/decorator_pattern.htm