[소프트웨어 공학] Design Patterns ②

양현지·2023년 8월 24일
1

소프트웨어공학

목록 보기
11/11

hjee02018.log : Design Patterns ① 의 싱글톤 패턴에 대해 더 자세히 살펴보고자 한다.

1. 싱글톤 패턴(Creational Pattern)

싱글톤 패턴은 하나의 클래스에 오직 하나의 인스턴스만 가지는 패턴. 원래 클래스는 다수의 인스턴스를 가지는 반면 하나의 인스턴스만 가지게 하는 로직으로, 주로 데이터베이스 연결 모듈에 사용

ⓐ 생성자가 여러번 호출 되더라도 실제로 생성되는 개체는 "1개"
ⓑ 핵심은 생성자로의 접근을 제한하는 것

1) 구현

  • java
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();
    }
}
  • javascript
class Singleton{
  constructor(){
    if(!Singleton.instance){
      Singleton.instance=this
    }
    return Singleton.instance
  }
  getInstance(){
    return this.instance
  }   
}
const a = new Singleton()
const b = new Singleton()
  • c++
    getInstance() -> if(instance==null) : call Singleton(); else return instance;
public class Singleton {
private:
	static Singleton instance;

    // "private 생성자"로 외부에서 인스턴스 생성을 막음
    Singleton() {
    }
public:
    static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }

    // 기타 메서드들
    void doSomething() {
        // ...
    }
}

2) 데이터베이스 연결 모듈

아래의 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)

3) Node.js에서 MySQL 연동하기

  • 자바스크립트 ver.
    모듈a와 모듈b는 각각 pool(하나의 인스턴스)를 사용해 쿼리를 보냄
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;
}        

2) 싱글톤 패턴의 장/단점

① 장점

  • 재사용성 향상
  • 유지보수 용이성
  • 자원의 절약
  • 전역적인 접근

② 단점

  • 전역 상태 유지로 인해 객체간 결합도, 의존도가 높아짐
  • TDD 가 어려움 (의존성 주입,DI를 통해 해결)

    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) {
        // 데이터베이스에서 사용자 정보를 조회하는 코드
    }
}

0개의 댓글