-
Notifications
You must be signed in to change notification settings - Fork 24
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
把大象塞进冰箱,共分几步? #200
Comments
是不是可以不用写那么多struct, 直接把"behave"作为func来写呢? |
package main
import (
"fmt"
)
type Open func()
type PutInside func()
type Close func(check Check)
type Check func()
var NormalOpen Open = func() { fmt.Println("Normal Open") }
var NormalPutInside PutInside = func() { fmt.Println("Normal PutInside") }
var NormalClose Close = func(check Check) { fmt.Println("Normal Close"); if nil != check { check() } }
var NormalCheck Check = func() { fmt.Println("Normal Check") }
var PinPutInside PutInside = func() { fmt.Println("Pin PutInside") }
var PinCheck Check = func() { fmt.Println("Pin Check") }
func main() {
var open = NormalOpen
var putInside = PinPutInside
var close = NormalClose
var check = PinCheck
open()
putInside()
close(check)
} |
理论上完全可以的啦。所以经常有这种 func 与 interface 互换的模式: // Open 定义了一个打开的接口.
type Opener interface{ Open() }
// OpenHandler 定义了一个打开的行为.
type OpenHandler func()
// Open 让 OpenHandler 隐式实现了 Opener 接口.
func (o OpenHandler) Open() {o()}
// 1. 当你需要 Opener 接口,但是只有 OpenHandler 的时候,你可以直接用,因为 OpenHandler 已经实现了 Opener 接口,最多套一层 OpenHandler(yourFn)
// 2. 当你需要 OpenHandler 函数,但是只有 Opener 对象的时候,你可以直接使用 opener.Open 但是使用 interface 的方式,有个好处,那就是 IDE (如 goland ),可以 Go to Implementations, 或者 Go to Method Specifications,阅读代码,非常方便 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
把大象塞进冰箱的OO实现
JAVA实现
GO实现
刘金良同学,按照Java的OO思路,迅速上手了一般GO实现,可是实际输出与预期不相符了,主要是密码冰箱重载的Check方法,竟然没有被调用到。
改一版,依然带着JAVA的印迹,区别如下:
这下可以正常输出了
再改第3版,更加gopher style了,对比JAVA,是不是感觉:
The text was updated successfully, but these errors were encountered: