Go 语言实现 23 种设计模式适配器
将一个类型的接口转换成客户希望的另外一个接口,使原本由于接口不兼容而不能一起工作的类可以一起工作。
Example_one
package mainimport "fmt"// Adaptee 适配者
type MyLegacyPrinter struct{}func (l *MyLegacyPrinter) Print(s string) (newMsg string) {newMsg = fmt.Sprintf("Legacy Printer: %s\n", s)println(newMsg)return
}// 目标抽象类
type LegacyPrinter interface {Print(s string) string
}// 客户要求接口
type ModernPrinter interface {PrintStored() string
}// 适配器
type PrinterAdapter struct {OldPrinter LegacyPrinterMsg 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
}func main() {// 旧的使用方式var old_adapter MyLegacyPrinterold_adapter.Print("Old ")// 适配器模式msg := "New"new_adapter := PrinterAdapter{OldPrinter: &MyLegacyPrinter{}, Msg: msg}returnMsg := new_adapter.PrintStored()fmt.Print(returnMsg)
}