35 lines
609 B
Go
35 lines
609 B
Go
|
package tools
|
|||
|
|
|||
|
import (
|
|||
|
"sync"
|
|||
|
)
|
|||
|
|
|||
|
type ProductCounter struct {
|
|||
|
mu sync.Mutex
|
|||
|
counters map[string]int
|
|||
|
}
|
|||
|
|
|||
|
func NewProductCounter() *ProductCounter {
|
|||
|
return &ProductCounter{
|
|||
|
counters: make(map[string]int),
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
func (pc *ProductCounter) GetNextProductNumber(categoryID string) int {
|
|||
|
pc.mu.Lock()
|
|||
|
defer pc.mu.Unlock()
|
|||
|
|
|||
|
// 如果之前没有这个分类的计数器,初始化为1
|
|||
|
if _, ok := pc.counters[categoryID]; !ok {
|
|||
|
pc.counters[categoryID] = 1
|
|||
|
}
|
|||
|
|
|||
|
// 生成商品编号
|
|||
|
productNumber := pc.counters[categoryID]
|
|||
|
|
|||
|
// 增加计数器
|
|||
|
pc.counters[categoryID]++
|
|||
|
|
|||
|
return productNumber
|
|||
|
}
|