Skip to content

Commit 1a63a92

Browse files
committed
Adding adapter pattern
1 parent 965f305 commit 1a63a92

File tree

3 files changed

+59
-1
lines changed

3 files changed

+59
-1
lines changed
Original file line numberDiff line numberDiff line change
@@ -1 +1,6 @@
1-
# Adapter pattern
1+
# Adapter pattern
2+
3+
This pattern is used when we have an old implementation and we need to add new functionality to it.
4+
By the Open/Closed principle, which means Open for extension, Closed for modification, we cannot just modify
5+
the "legacy" interface/struct. We should create a new interface/struct adapter so we still support "legacy" functionality
6+
whilst adding new to it.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package adapter
2+
3+
type Printer interface {
4+
Print(string) string
5+
}
6+
7+
type MyPrinter struct{}
8+
9+
func (m MyPrinter) Print(input string) string {
10+
return "legacy printing: " + input
11+
}
12+
13+
type ModernPrinter interface {
14+
PrintStored() string
15+
}
16+
17+
type PrinterAdapter struct {
18+
Printer
19+
Msg string
20+
}
21+
22+
func (p PrinterAdapter) PrintStored() string {
23+
if p.Printer != nil {
24+
return p.Print(p.Msg)
25+
}
26+
return "modern printing: " + p.Msg
27+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package adapter
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/assert"
7+
)
8+
9+
func TestAdapter(t *testing.T) {
10+
var input = "hello"
11+
12+
t.Run("adapter with old implementation", func(t *testing.T) {
13+
printer := PrinterAdapter{Printer: MyPrinter{}, Msg: input}
14+
want := "legacy printing: " + input
15+
16+
assert.Equal(t, want, printer.Print(input))
17+
assert.Equal(t, want, printer.PrintStored())
18+
})
19+
20+
t.Run("adapter with new implementation", func(t *testing.T) {
21+
printer := PrinterAdapter{Msg: input}
22+
want := "modern printing: " + input
23+
24+
assert.Equal(t, want, printer.PrintStored())
25+
})
26+
}

0 commit comments

Comments
 (0)