Skip to content

Commit

Permalink
cmmand
Browse files Browse the repository at this point in the history
  • Loading branch information
daoyuly committed Nov 1, 2023
1 parent 955b8ac commit 5973037
Show file tree
Hide file tree
Showing 3 changed files with 99 additions and 0 deletions.
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
# design-patterns-in-python
https://github.com/Sean-Bradley/Design-Patterns-In-Python/tree/master

# design-patterns-in-go
https://github.com/mohuishou/go-design-pattern/tree/master

# 其他参考

## python
- https://github.com/faif/python-patterns/tree/master
- https://github.com/RefactoringGuru/design-patterns-python/tree/main/src
- https://github.com/gennad/Design-Patterns-in-Python/tree/master
Expand All @@ -11,3 +16,9 @@ https://github.com/Sean-Bradley/Design-Patterns-In-Python/tree/master
- https://github.com/PacktPublishing/Mastering-Python-Design-Patterns-Second-Edition/tree/master
- https://github.com/Sean-Bradley/Design-Patterns-In-Python
- https://github.com/Sean-Bradley/Design-Patterns-In-Python/tree/master

## go
- https://github.com/tmrts/go-patterns/tree/master
- https://github.com/ruanrunxue/Practice-Design-Pattern--Go-Implementation/tree/main


29 changes: 29 additions & 0 deletions command/go/case1/command.go
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
}
59 changes: 59 additions & 0 deletions command/go/case1/command_test.go
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

}
}

}

0 comments on commit 5973037

Please sign in to comment.