Last active
December 26, 2015 21:38
-
-
Save hongruiqi/7216936 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "sync" | |
type SingleCounter struct { | |
count int | |
} | |
var counter *SingleCounter | |
type Manager struct { | |
counter *SingleCounter | |
once sync.Once | |
} | |
func NewManager() *Manager { | |
manager := new(Manager) | |
manager.once.Do(func() { | |
counter = new(SingleCounter) | |
}) | |
manager.counter = counter | |
return manager | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "sync" | |
type SingleCounter struct { | |
count int | |
} | |
var counter *SingleCounter | |
var counterInit sync.Once | |
func getCounter() *SingleCounter { | |
counterInit.Do(func() { | |
counter = new(SingleCounter) | |
}) | |
return counter | |
} | |
type Manager struct { | |
counter *SingleCounter | |
} | |
func NewManager() *Manager { | |
return &Manager{counter: getCounter()} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "sync" | |
type SingleCounter struct { | |
count int | |
} | |
var getCounter = func() func() *SingleCounter { | |
var counter *SingleCounter | |
var counterInit sync.Once | |
return func() *SingleCounter { | |
counterInit.Do(func() { | |
counter = new(SingleCounter) | |
}) | |
return counter | |
} | |
}() | |
type Manager struct { | |
counter *SingleCounter | |
} | |
func NewManager() *Manager { | |
return &Manager{counter: getCounter()} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment