/**
实现了PS/2 转换成USB目标接口(适配)
*/
/*
什么是适配器模式?
- 将一个类接口转换成客户希望的另一个接口。Adapter模式使用原本由接口不兼容而不能一起工作的
那些类可以在一起工作。
模式中的角色
- 目标接口(Target):客户所期待的接口。目标可以是具体的或抽象的类,也可是接口。
- 需要适配的类(Adaptee):需要适配的类或适配者类
- 适配器(Adapter): 通过包装一个需要适配的对象,把原接口转换成目标接口。
*/
package adapter
import "fmt"
type PSKeyword struct {
}
func NewPSKeyword() *PSKeyword {
return &PSKeyword{}
}
func (ps *PSKeyword) Print() {
for i:='a'; i <= 'z'; i++{
fmt.Printf("%c ",i)
}
fmt.Println()
}
type IUsb interface {
HandlePrint()
}
type UsbKeyword struct {
Keyword *PSKeyword
}
func NewUsbKeyword(ps *PSKeyword) *UsbKeyword {
return &UsbKeyword{Keyword: ps}
}
func (u *UsbKeyword) HandlePrint() {
u.Keyword.Print()
}
type MacBook struct {
}
func NewMacBook() *MacBook {
return &MacBook{}
}
func (m *MacBook)Print(usb IUsb) {
usb.HandlePrint()
}
//测试代码
package adapter
import(
"testing"
)
func TestPrint(t *testing.T) {
mackBook := NewMacBook()
psKeyword := NewPSKeyword()
usbKeyword := NewUsbKeyword(psKeyword)
mackBook.Print(usbKeyword)
}
//执行结果
go test -v
=== RUN TestPrint
a b c d e f g h i j k l m n o p q r s t u v w x y z
--- PASS: TestPrint (0.00s)
PASS
ok mlemon_ssh/factory/adapter 0.596s
2适配者模式-golang
最新推荐文章于 2024-09-12 17:23:35 发布