adapter.go
package adapter import ( "fmt" ) type LegacyPrinter interface { Print(s string) string } type MyLegacyPrinter struct{} func (l *MyLegacyPrinter) Print(s string) (newMsg string) { newMsg = fmt.Sprintf("Legacy Printer: %s\n", s) fmt.Println(newMsg) return } type ModernPrinter interface { PrintStored() string } type PrinterAdapter struct { OldPrinter LegacyPrinter Msg string } func (p *PrinterAdapter) PrintStored() (newMsg string) { if p.OldPrinter != nil { newMsg = fmt.Sprintf("Adapter: %s", p.Msg) newMsg = p.OldPrinter.Print(newMsg) } else { newMsg = p.Msg } return }
adapter_test.go
package adapter import ( "testing" ) func TestAdapter(t *testing.T) { msg := "Hello World!" adapter := PrinterAdapter{OldPrinter: &MyLegacyPrinter{}, Msg: msg} returnnedMsg := adapter.PrintStored() if returnnedMsg != "Legacy Printer: Adapter: Hello World!\n" { t.Errorf("Message didn't match: %s\n", returnnedMsg) } adapter = PrinterAdapter{OldPrinter: nil, Msg: msg} returnnedMsg = adapter.PrintStored() if returnnedMsg != "Hello World!" { t.Errorf("Message didn't match: %s\n", returnnedMsg) } }