#设计模式 #GO

如何在 Go 语言中实现单例模式

有关单例模式的相关内容可以参考《设计模式之单例模式》 单例模式的核心在于保证系统中一个类只有一个实例且该实例易于外界访问。 1. 非线程安全 Lazy 方式 非线程安全的单例模式是最常见的实现方式,但是它不能在多线程情况下使用,在 Go 中实现如: type Singleton struct { // something } var instance *Singleton func GetInstance() *Singleton { if instance == nil { instance = &Singleton{} } return instance } 这种写法对应着 CPP 中的实现方式。 2. 线程锁方式 在 Go 语言中提供了包 sync/mutex 用于构建多个 goroutine 间的同步逻辑。 在 Go 中使用线程锁实现的单例模式,如下: type Singleton struct { // something } var ( instance *Singleton mtx Sync.Mutex ) func GetInstance() *Singleton { mtx. ...

#go #golang #hugo #development

Getting Started with Hugo

Step 1. Install Hugo Goto hugo releases and download the appropriate version for your os and architecture. Save it somewhere specific as we will be using it in the next step. More complete instructions are available at installing hugo Step 2. Build the Docs Hugo has its own example site which happens to also be the documentation site you are reading right now. Follow the following steps: Clone the hugo repository Go into the repo Run hugo in server mode and build the docs Open your browser to http://localhost:1313 Corresponding pseudo commands: ...