Reading notes -- Singleton pattern
Posted on 2006-07-09 12:42 Jedi 閱讀(303) 評論(0) 編輯 收藏 所屬分類: Design Patterns
public
?
class
?Singleton?{
???? private ? volatile ? static ?Singleton?uniqueInstance;
???? private ?Singleton(){
????????
????}
????
???? public ? static ?Singleton?getInstance(){
???????? if (uniqueInstance == null ){
???????????? synchronized (Singleton. class ){
???????????????? if (uniqueInstance == null ){
????????????????????uniqueInstance? = ? new ?Singleton();
????????????????}
????????????}
????????}????????
???????? return ?uniqueInstance;?
????}
}
???? private ? volatile ? static ?Singleton?uniqueInstance;
???? private ?Singleton(){
????????
????}
????
???? public ? static ?Singleton?getInstance(){
???????? if (uniqueInstance == null ){
???????????? synchronized (Singleton. class ){
???????????????? if (uniqueInstance == null ){
????????????????????uniqueInstance? = ? new ?Singleton();
????????????????}
????????????}
????????}????????
???????? return ?uniqueInstance;?
????}
}
1. private constructor
2. static getInstance
3. syncronized..waste a lot of time
4. double check..modified syncronize, so time-waste might occurs only when first time the instance construct