本文共 1038 字,大约阅读时间需要 3 分钟。
饿汉模式是最简单的实现方式,直接在类初始化时创建对象实例,并将其存储起来等待使用。懒汉模式则稍微复杂一些,会在第一次需要使用对象实例时创建实例。两种方式都能实现单例的功能,但懒汉模式在某些高并发场景下需要额外的锁机制来保证线程安全。
单例模式的主要应用场景是需要全局唯一对象的场合。比如手机应用程序的主进程,或者Java Spring中的Bean容器。这些场景都需要确保系统运行中只有一个对象实例。
package mainimport ( "fmt" "sync")type Singleton struct { Name string}var singletonHungry = &Singleton{ Name: "singletonHungry",}var singletonLazy *Singletonvar once sync.Oncefunc GetSingletonHungry() *Singleton { return singletonHungry}func GetSingletonLazy() *Singleton { if singletonLazy == nil { once.Do(func() { singletonLazy = &Singleton{ Name: "singletonLazy", } }) } return singletonLazy}func main() { fmt.Println("设计一个单例模式") fmt.Println("好的老板") fmt.Println(GetSingletonHungry().Name) fmt.Println(GetSingletonLazy().Name)} 这个代码实现了懒汉模式和饿汉模式两种单例实现方式。懒汉模式通过sync.Once保证了线程安全,而饿汉模式则直接在类初始化时创建对象实例。无论是哪种模式,都确保了系统中只有一个对象实例。
转载地址:http://cpod.baihongyu.com/