프로그램을 설계할 때 발생했던 문제점 들을 객체 간의 상호관계 등을 이용하여 해결할 수 있도록 하나의 '규약'형태로 만들어 놓은 것
const obj = {
a : 27
}
const obj2 = {
a : 27
}
// obj와 obj2는 다르다.
class Singleton {
constructor() {
if ( !Singleton.instance ) {
Singleton.instance = this
}
return Singleton.instance
}
getInstance() {
return this.instance
}
}
const o1 = new Singleton()
const o2 = new Singleton()
// o1 과 o2는 같다.
class Singleton {
private static class singleInstanceHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static synchronized Singleton getInstance() {
return singleInstanceHolder.INSTANCE;
}
}
public class HelloWorld {
public static void main(String[] args) {
Singleton a = Singleton.getInstance();
Singleton b = Singleton.getInstance();
System.out.println(a.hashCode());
System.out.println(b.hashCode());
if ( a == b ) {
System.out.println("아싸좋구나");
}
}
}
싱글톤 패턴은 Node JS 에서 MongoDB 데이터베이스 연결할 때 쓰는 mongoose 모듈에서 볼 수 있다.