hjee02018.log : Design Patterns ① 의 싱글톤 패턴에 대해 더 자세히 살펴보고자 한다.
ⓐ 생성자가 여러번 호출 되더라도 실제로 생성되는 개체는 "1개"
ⓑ 핵심은 생성자로의 접근을 제한하는 것
class Singleton{
private static class singleInstanceHolder{
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstnace(){
return singleInstanceHolder.INSTANCE;
}
}
public class Main{
public static void main(String[] args){
Singleton a = Singleton.getInstance();
Singleton b = Singleton.getInstance();
}
}
class Singleton{
constructor(){
if(!Singleton.instance){
Singleton.instance=this
}
return Singleton.instance
}
getInstance(){
return this.instance
}
}
const a = new Singleton()
const b = new Singleton()
public class Singleton {
private:
static Singleton instance;
// "private 생성자"로 외부에서 인스턴스 생성을 막음
Singleton() {
}
public:
static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
// 기타 메서드들
void doSomething() {
// ...
}
}
아래의 a와 b는 각각 DB.instance라는 동일한 인스턴스를 가짐
const URL = 'mariadb://localhost:3306/root'
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)
const mysql = require('mysql');
const pool = mysql.createPool({
connectionLimit : 10,
host : 'example.org',
user : 'root',
password : '~',
database : 'mysqlDb'
});
pool.connect();
// Module A
pool.query(query, function(error,results,fields){
if(error) throw error;
}
// Module B
pool.query(query, function(error,results,fields){
if(error) throw error;
}
① 장점
② 단점
TDD란?
: Test Driven Development, 독립적인 단위 테스트로 각각의 테스트 단위를 어떤 순서로든 실행할 수 있어야함
③ 의존성 주입(Dependency Injection, DI)이란?
'UserService'클래스는 생성자 호출 시 'UserRepository'인터페이스를 의존성으로 받음
-> 테스트 시 가짜 'UserRepository'를 주입하여 테스트를 수행
// 의존성이 주입되는 클래스
public class UserService {
private UserRepository userRepository;
// 생성자를 통한 의존성 주입
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User getUserById(int userId) {
return userRepository.getUserById(userId);
}
}
// 의존성을 주입하는 인터페이스 또는 클래스
public interface UserRepository {
User getUserById(int userId);
}
// 실제 의존성 주입 구현 예시
public class DatabaseUserRepository implements UserRepository {
// 데이터베이스와의 연결 등의 코드
@Override
public User getUserById(int userId) {
// 데이터베이스에서 사용자 정보를 조회하는 코드
}
}