场景
老板:一直听你说面向接口编程,那你举一个设计模式告诉我什么叫tm的面向接口编程
你:好的老板,那就使用桥接模式
方案
桥接模式就是面向接口编程的最好体现.
桥接模式就是自己创建一个所谓的桥接器,这个桥接器里面有一个属性是一个接口类型的,这个桥接器不维护接口的实现,而是open一个方法,让桥接器的使用者把实现传递给它,然后桥接器用这个真正的接口实现去干活.
桥接器就是面向接口编程,通过接口嫁接任意的实现,达到可扩展的效果.假如当前的实现不满足要求,那么随时随地增加实现去扩展.
实现
see:https://github.com/jjtHappy/design-pattern-so-simple
package main
import "fmt"
type Interface interface {
foo() string
}
type InterfaceImplA struct {
}
type InterfaceImplB struct {
}
func (*InterfaceImplA) foo() string {
return "实现A在干活"
}
func (*InterfaceImplB) foo() string {
return "实现B在干活"
}
type Bridge struct {
worker Interface
}
func (m *Bridge) Init(p Interface) {
m.worker = p
}
func (m *Bridge) DoSomething() string {
return m.worker.foo()
}
func main() {
fmt.Println("告诉我啥叫tm的面向接口编程")
fmt.Println("这就是tm的面向接口编程")
b := &Bridge{}
b.Init(&InterfaceImplA{})
fmt.Println(b.DoSomething())
b.Init(&InterfaceImplB{})
fmt.Println(b.DoSomething())
}