Skip to content

Commit 23101a3

Browse files
committed
add adapter pattern
1 parent bc38b71 commit 23101a3

File tree

3 files changed

+54
-0
lines changed

3 files changed

+54
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,4 @@
1313

1414
* [Composite](structural/composite) [:notebook:](http://en.wikipedia.org/wiki/Composite_pattern)
1515
* [Binary Tree compositions](structural/binary-tree-compositions) [:notebook:](https://en.wikipedia.org/wiki/Binary_tree)
16+
* [Adapter](structural/adapter) [:notebook:](https://en.wikipedia.org/wiki/Adapter)

structural/adapter/adapter.go

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package main
2+
3+
import "fmt"
4+
5+
type LegacyPrinter interface {
6+
Print(s string) string
7+
}
8+
9+
type MyLegacyPrinter struct{}
10+
11+
type ModernPrinter interface {
12+
PrintStored() string
13+
}
14+
15+
type PrinterAdapter struct {
16+
OldPrinter LegacyPrinter
17+
Msg string
18+
}
19+
20+
func (p *PrinterAdapter) PrintStored() (newMsg string) {
21+
if p.OldPrinter != nil {
22+
newMsg = fmt.Sprintf("Adapter: %s", p.Msg)
23+
newMsg = p.OldPrinter.Print(newMsg)
24+
} else {
25+
newMsg = p.Msg
26+
}
27+
return
28+
}
29+
30+
func (l *MyLegacyPrinter) Print(s string) (newMsg string) {
31+
newMsg = fmt.Sprintf("Legacy Printer: %s\n", s)
32+
println(newMsg)
33+
return
34+
}
35+
36+
func main() {
37+
fmt.Println("vim-go")
38+
}

structural/adapter/adapter_test.go

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package main
2+
3+
import "testing"
4+
5+
func TestAdater(t *testing.T) {
6+
msg := "Hello world!!!"
7+
adapter := PrinterAdapter{
8+
OldPrinter: &MyLegacyPrinter{},
9+
Msg: msg,
10+
}
11+
returnedMsg := adapter.PrintStored()
12+
if returnedMsg != "Legacy Printer: Adapter: Hello world!!!\n" {
13+
t.Errorf("Message didnt match: %s\n", returnedMsg)
14+
}
15+
}

0 commit comments

Comments
 (0)