单例模式(Singleton Pattern) 是一种创建型设计模式,它确保一个类只有一个实例,并提供一个全局访问点来获取该实例。这个模式在多种编程语言和框架中都有广泛应用,特别是在需要控制资源访问或实现全局状态管理的场景中。
单例模式—题目链接
package mainimport ("bufio""fmt""os""strconv""strings""sync"
)type ShopCarManager struct {item_map map[string]int
}func (s *ShopCarManager) AddItemToCar(itemName string, count int) {if _, ok := s.item_map[itemName]; !ok {s.item_map[itemName] = count} else {s.item_map[itemName] += count}
}func (s *ShopCarManager) PrintAllItemInfo() {for k := range s.item_map {fmt.Println(k, s.item_map[k])}
}var once sync.Once
var shopCarInstance *ShopCarManagerfunc GetShowCarInstance() *ShopCarManager {once.Do(func() {shopCarInstance = &ShopCarManager{make(map[string]int)}})return shopCarInstance
}func main() {var shop_instance = GetShowCarInstance()var reader = bufio.NewScanner(os.Stdin)for reader.Scan() {if reader.Text() == "" {break}var str = reader.Text()var item_info = strings.Split(str, " ")var count, _ = strconv.Atoi(item_info[1])shop_instance.AddItemToCar(item_info[0], count)}shop_instance.PrintAllItemInfo()
}