注:本文已发布超过一年,请注意您所使用工具的相关版本是否适用
序
笔记
代码实现
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
|
package mediator
import ( "fmt" "reflect" )
type Input string
func (i Input) String() string { return string(i) }
type Selection string
func (s Selection) Selected() string { return string(s) }
type Button struct { onClick func() }
func (b *Button) SetOnClick(f func()) { b.onClick = f }
type IMediator interface { HandleEvent(component interface{}) }
type Dialog struct { LoginButton *Button RegButton *Button Selection *Selection UsernameInput *Input PasswordInput *Input RepeatPasswordInput *Input }
func (d *Dialog) HandleEvent(component interface{}) { switch { case reflect.DeepEqual(component, d.Selection): if d.Selection.Selected() == "登录" { fmt.Println("select login") fmt.Printf("show: %s\n", d.UsernameInput) fmt.Printf("show: %s\n", d.PasswordInput) } else if d.Selection.Selected() == "注册" { fmt.Println("select register") fmt.Printf("show: %s\n", d.UsernameInput) fmt.Printf("show: %s\n", d.PasswordInput) fmt.Printf("show: %s\n", d.RepeatPasswordInput) } } }
|
测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| package mediator
import "testing"
func TestDemo(t *testing.T) { usernameInput := Input("username input") passwordInput := Input("password input") repeatPwdInput := Input("repeat password input")
selection := Selection("登录") d := &Dialog{ Selection: &selection, UsernameInput: &usernameInput, PasswordInput: &passwordInput, RepeatPasswordInput: &repeatPwdInput, } d.HandleEvent(&selection)
regSelection := Selection("注册") d.Selection = ®Selection d.HandleEvent(®Selection) }
|
关注我获取更新
猜你喜欢