-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
99 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
package case1 | ||
|
||
import "fmt" | ||
|
||
type ICommand interface { | ||
execute() error | ||
} | ||
|
||
type TurnOnCommand struct{} | ||
|
||
func NewTurnOnCommand() *TurnOnCommand { | ||
return &TurnOnCommand{} | ||
} | ||
|
||
func (t *TurnOnCommand) execute() error { | ||
fmt.Println("command: turn on") | ||
return nil | ||
} | ||
|
||
type TurnOffCommand struct{} | ||
|
||
func NewTurnOffCommand() *TurnOffCommand { | ||
return &TurnOffCommand{} | ||
} | ||
|
||
func (t *TurnOffCommand) execute() error { | ||
fmt.Println("command: turn off") | ||
return nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
package case1 | ||
|
||
import ( | ||
"fmt" | ||
"testing" | ||
"time" | ||
) | ||
|
||
func TextCommandDemo(t *testing.T) { | ||
eventChan := make(chan string) | ||
defer close(eventChan) | ||
|
||
// 用于测试,模拟来自客户端的事件 | ||
go func() { | ||
events := []string{"turnOn", "turnOff", "turnOn"} | ||
for _, e := range events { | ||
eventChan <- e | ||
} | ||
}() | ||
|
||
// 使用命令队列缓存命令 | ||
commands := make(chan ICommand, 1000) | ||
defer close(commands) | ||
|
||
go func() { | ||
for { | ||
event, ok := <-eventChan | ||
|
||
if !ok { | ||
return | ||
} | ||
|
||
var command ICommand | ||
switch event { | ||
case "turnOn": | ||
command = NewTurnOnCommand() | ||
case "turnOff": | ||
command = NewTurnOffCommand() | ||
} | ||
|
||
commands <- command | ||
} | ||
}() | ||
|
||
for { | ||
select { | ||
case c := <-commands: | ||
ok := c.execute() | ||
if ok != nil { | ||
print("executing error") | ||
} | ||
case <-time.After(2 * time.Second): | ||
fmt.Println("timeout 2s") | ||
return | ||
|
||
} | ||
} | ||
|
||
} |