티스토리 뷰

Java

Singleton Pattern

techbard 2016.07.22 13:56



# What is a singleton?


- There are situations where exactly one object of a particula type is needed.

- Where it would be bad to have any more than one object of a particular class.

- Device drivers, registry setting manager, or other system - wide shared objects are the classic examples.

- Singleton objects also make sense where the state of an object consumes a lot of memory, and just one version of that state is sufficient for the entire application.



# A singleton object must satisfy two attributes

- Exactly one (well actually, at most one) instance of the object should exist.

- Everyone must be able to access that one singleton object. (This means that the object needs to be globally accessible.)



# code


public class Singleton {

    

    private static Singleton singleton;

    

    private Singleton() {}

    

    public static synchronized Singleton getInstance() {

if (singleton == null) {

   singleton = new Singleton();

}

return singleton;

    }

}



# Singleton - another ver.


public class Singleton {

    // volatile is 'synchronized' on the variable itself

    private volatile static Singleton singleton = new Singleton();

    

    private Singleton() {}

    

    public static Singleton getInstance() {

return singleton;

    }

}



# Declaring a volatile Java variable means: The value of this variable will never be cached thread-locally: all reads and writes will go straight to "main memory"; Access to the variable acts as though it is enclosed in a synchronized block, synchronized on itself.


댓글
댓글쓰기 폼
공지사항
Total
407,537
Today
11
Yesterday
19
«   2019/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30          
글 보관함