1
0
Fork 0
design-patterns/go/adapter/main.go

64 lines
1.3 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
/*
实例
汤宝宝有一个苹果手机手机原配lightning接口为了连接Type-C接口的充电器他需要一个转换器适配器来实现这个功能。
*/
import "fmt"
// 充电器类
type Charger struct{}
func (c *Charger) Connect(typec TypeCInterface) {
typec.TypeCCharging()
fmt.Println("手机开始充电!")
fmt.Println()
}
// Type-C充电接口的接口
type TypeCInterface interface {
TypeCCharging()
}
// 具体实现类
type TypeC struct{}
func (t *TypeC) TypeCCharging() {
fmt.Println("Type-C接口连接中...")
}
type Lightning struct{}
func (l *Lightning) LightningCharging() {
fmt.Println("Lightning接口连接中...")
}
// 适配器类
type LightningToTypeCAdapter struct {
lightning *Lightning
}
func (l *LightningToTypeCAdapter) TypeCCharging() {
fmt.Println("Type-C适配器转换中...")
l.lightning.LightningCharging()
}
func main() {
charger := &Charger{}
lightning := &Lightning{}
typec := &TypeC{}
fmt.Println("============= 适配器模式 =============")
fmt.Println("使用Type-C充电器给小米手机充电")
charger.Connect(typec)
fmt.Println("使用Lightning接口转换器给苹果手机充电")
adapter := &LightningToTypeCAdapter{lightning: lightning}
charger.Connect(adapter)
fmt.Println("=========== 适配器模式结束 ===========")
}