'면접을 위한 CS 전공지식 노트' 책을 읽으면서 전공 지식에 대해 정리하려고 한다.
면접을 위한 CS 전공지식 노트
프로그램을 설계할 때 발생했던 문제점들을 객체 간의 상호 관계 등을 이용해 해결할 수 있도록 하나의 '규약' 형태로 만들어둔 것
하나의 클래스에 오직 하나의 Instance 만 가지는 패턴
- ex) 데이터베이스 연결 모듈
하나의 인스턴스를 만들어두고 해당 인스턴스를 다른 모듈들이 공유하며 사용한다.
그래서 인스턴스 생성 시 드는 비용이 줄어드는 장점이 있고, 역으로는 의존성이 높아진다는 단점이 있다.
JavaScript 에서는 리터럴 {} 또는 new Object로 객체를 생성하게 되면 어떤 객체와도 같지 않다.
-> 즉, 그 자체로도 싱글톤 패턴 구현 가능하다.
const obj = {
a: 27
}
const obj2 = {
a: 27
}
console.log(obj === obj2)
// false
위의 코드는 각 다른 인스턴스를 가지는 것을 확인할 수 있는데
class Singleton {
constructor() {
if (!Singleton.instance) {
Singleton.instance = this
}
return Singleton.instance
}
getInstance() {
return this.instance
}
}
const a = new Singleton()
const b = new Singleton()
console.log(a === b) // true
Singleton.instance라는 하나의 인스턴스를 가지는 Singleton 클래스했을 때는 true로 나오는 것을 보면 같은 인스턴스를 가지는 것을 알 수 있다.
즉,
JavaScript에서는리터럴 {}또는new Object로 객체를 생성하면 싱글톤 패턴 구현 가능
이런 형태로 데이터베이스 연결 모듈도 DB 클래스를 만들어서 하나의 인스턴스를 기반으로 생성할 수 있다.
const URL = 'mongodb://localhost:27017/jojehun' const createConnection = url => ({"url" : url}) class DB { constructor(url) { if (!DB.instance) { DB.instance = createConnection(url) } return DB.instance } connect() { return this.instance } } const a = new DB(URL) const b = new DB(URL) console.log(a === b) // true
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(true);
}
}
}
출력 결과
705927765
705927765
true
실제로 싱글톤 패턴은 Node.js에서 MongoDB 데이터베이스를 연결할 때 쓰는 mongoose 모듈에서 볼 수 있다.
mongoose의 데이터베이스를 연결할 때 쓰는 connect()라는 함수는 싱글톤 인스턴스를 반환한다. 다음은 connect() 함수를 구현할 때 쓰인 실제 코드다.
Mongoose.prototype.connect = function(uri, options, callback) {
const _mongoose = this instanceof Mongoose ? this : mongoose;
const conn = _mongoose.connection;
return _mongoose._promiseOrCallback(callback, cb => {
conn.openUri(uri, options, err => {
if (err != null) {
return cb(err);
}
return cb(null, _mongoose);
});
});
};
// 메인 모듈
const mysql = require('mysql');
const pool = mysql.createPool({
connectionLimit: 10,
host: 'example.org',
user: 'jojehun',
password: 'jojehun',
database: '디비디비'
});
pool.connect();
// 모듈 A
pool.query(query, function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
// 모듈 B
pool.query(query, function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
위 형식으로 쓰인다.
위 단점과 같이 모듈 간의 결합을 강하게 만들 수 있다는 단점이 있는데 이 때 의존성 주입 (Dependency Injection) 을 통해 모듈 간의 결합을 조금 느슨하게 만들어 해결도 가능하다.
의존성 = 종속성
ex) A가 B에 의존성이 있다는 것은 B의 변경사항에 따라 A 또한 변해야 된다는 것을 의미한다.

위 그림처럼 메인 모듈이 '직접' 다른 하위 모듈에 대한 의존성을 주는 것보다 중간에 의존성 주입자가 이 부분을 가로채 메인 모듈이 '간접'적으로 의존성을 주입하는 방식이다.
메인 모듈(상위 모듈)은 하위 모듈에 대한 의존성이 떨어지게 된다. 이를 ‘디커플링이 된다’고도 한다.
모듈들이 더욱더 분리되므로 클래스 수가 늘어나 복잡성이 증가될 수 있으며 약간의 런타임 페널티가 생기기도 한다.
의존성 주입은 의존성 주입 원칙을 지키며 만들어야 하며 원칙은 다음과 같다.
상위 모듈은 하위 모듈에서 어떠한 것도 가져오지 않아야 한다.
둘 다 추상화에 의존해야 하며, 이때 추상화는 세부 사항에 의존하지 말아야 한다.