设计模式不分语言,是一种思维层面的体现,但是不能在不同语言中使用同一套实现(每种语言有不同的特性),比如go,本身是没有继承一说,但是通过结构体的组合来实现语义上的继承。而多态也是通过接口的方式来实现的。
下方的图来自于大佬博客,贴在这里方便查看!!!
设计原则
设计模式
结构型模式
适配器模式
适配器模式将不兼容的接口转换为可兼容的接口,让原本由于接口不兼容而不能一起工作的类可以一起工作。
实现方式分为:类适配器(继承实现) 和 对象适配器(组合实现)
对于实现方式的选择:
-
适配的接口不多,两种都可。
-
适配的接口很多
- 需要大量修改,对象适配器
- 不需要大量修改,类适配器
//场景是需要创建不同的server,不同的server有不同的创建接口。
type ICreateServer interface {
CreateServer(cpu, mem float64) error
}
//AWS创建接口
type AWSClient struct {
}
//启动AWS实例
func (a *AWSClient) RunInstance(cpu, mem float64) error {
fmt.Printf("AWS实例启动了,我的配置是:cpu %v,mem %v", cpu, mem)
return nil
}
//AWS适配器
type AWSClientAdapter struct {
client AWSClient
}
func (a *AWSClientAdapter) CreateServer(cpu, mem float64) error {
a.client.RunInstance(cpu,mem)
return nil
}
//阿里云接口
type AliyunClient struct {
}
func (a *AliyunClient) RunInstance(cpu, mem int) error {
fmt.Printf("阿里云实例启动了,我的配置是:cpu %v,mem %v", cpu, mem)
return nil
}
//阿里云适配器
type AliyunClientAdapter struct {
client AliyunClient
}
func (a *AliyunClientAdapter) CreateServer(cpu, mem float64) error {
a.client.RunInstance(int(cpu), int(mem))
return nil
}