public class Singleton {
private static Singleton singletonObject;
private Singleton() {}
public static Singleton getSingletonObject() {
if (singletonObject == null) {
singletonObject = new Singleton();
}
return singletonObject;
}
}
public class Singleton {
private static Singleton singletonObject;
private Singleton() {}
public static synchronized Singleton getSingletonObject() {
if (singletonObject == null) {
singletonObject = new Singleton();
}
return singletonObject;
}
}
public class Singleton {
private static volatile Singleton singletonObject;
private Singleton() {}
public static Singleton getSingletonObject() {
if (singletonObject == null) {
synchronized (Singleton.class) {
if(singletonObject == null) {
singletonObject = new Singleton();
}
}
}
return singletonObject;
}
}
public class Singleton {
private static volatile Singleton singletonObject = new Singleton();
private Singleton() {}
public static Singleton getSingletonObject() {
return singletonObject;
}
}
Singleton.java >> ver.5
public class Singleton {
private Singleton() {}
private static class SingletonHolder {
public static final Singleton INSTANCE = new Singleton();
}
public static Singleton getSingletonObject() {
return SingletonHolder.INSTANCE;
}
}
public static void main(String[] args) {
//생성자에 private 키워드가 있기 때문에 new를 통해 인스턴스를 생성할 수 없다
//Singleton singleton = new Singleton();
Singleton s1 = Singleton.getSingletonObject();
Singleton s2 = Singleton.getSingletonObject();
System.out.println(s1);//com.algorithm.singletonpattern.Singleton@39ed3c8d
System.out.println(s2);//com.algorithm.singletonpattern.Singleton@39ed3c8d
}
'Dev.BackEnd > JAVA' 카테고리의 다른 글
[JAVA Adv] Blocking I/O, ServerSocket, Socket 그리고 Thread Pool (0) | 2017.01.22 |
---|---|
[JAVA Adv] StringBuffer vs StringBuilder 그리고 String (0) | 2016.12.08 |
[Java] 자바의 기본적인 이슈들 5가지 (3) | 2016.11.25 |
[JAVA Adv] Annotaion 에 대해서, (0) | 2016.10.29 |
[Java Adv] 16. Lambda Expression + Inner class, anonymous class (0) | 2016.10.25 |