반응형
Notice
Recent Posts
Recent Comments
Link
250x250
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

동글이의 STORY

싱글톤 패턴 본문

Javascript/자바스크립트 패턴

싱글톤 패턴

dongling 2024. 7. 3. 21:52
728x90
반응형
SMALL

🔶 싱글톤 패턴(singleton pattern)

  • 인스턴스(객체)를 애플리케이션 전체에서 공유하는 디자인 패턴
  • 전역 변수를 사용하지 않고도 해당 객체를 전역적으로 접근 할 수 있게 되며 공유 자원에 대한 동시 접근을 제어
    1. 자원 관리 : 객체 하나만 생성하기 때문에 자원 낭비 방지
    2. 전역 객체 : 전역 객체처럼 동작하므로, 여러 곳에서 접근 사용 가능
    3. 상태 유지 : 상태 유지 용이
    4. 안정성 : 다중 스레드 환경에서도 안정성 보장
    단점
    1. 의존성 문제 : 싱글톤 객체에 의존하는 다른 객체들이 있는 경우 의존성 문제 발생
    2. 테스트 어려움 : TDD에 걸림돌이 됨, 테스트 제어 어려움
    3. 객체의 역할이 명확하지 않음
    4. 유연성 제한 : 수정 불가, 상속을 통한 확장 불가
  • 장점

🔹 Class 문법 이용

  • 자바에서 싱글톤 패턴을 구현하는 방식을 흉내
let instance; // 싱글톤으로 생성/관리되는 객체가 담기는 변수
let count = 0; // 전역 스코프에서 관리되는 데이터

class Counter {
	constructor() { 
		if (instance) {
			throw new Error("생성된 인스턴스가 이미 존재합니다!");
		}
			instance = this; // new Counter()로 최초로 생성된 인스턴스를 저장
	}
		
	getInstance() { return this; }
	getCount() { return count; } 
	increment() { 
		return ++count; // count를 1만큼 증가시키고 그 값을 반환
	}
	decrement() { 
		return --count; // count를 1만큼 감소시키고 그 값을 반환
	}
}
	
const singletonCounter = Object.freeze(new Counter()); 
export default singletonCounter;
  • Counter 클래스 자체는 export되고 있지 않기 때문에 다른 자바스크립트 파일들에서는 new Counter()를 실행하여 새로운 Counter 인스터스를 생성 할 수 없다.
  • 만일 new Counter() 실행이 가능했더라도, instance 변수가 이미 다른 Counter 인스턴스로 초기화되었는지를 체크해주는 방어로직이 constructor에서 실행되기 때문에 Counter 인스턴스는 싱클톤으로 유지 가능
  • Object.freeze() : 해당 객체가 수정될 수 없도록 얼리는 기능을 수행

🔹 생성자 이용

  • 함수, 생성자, 프로토타입을 사용하여 싱글톤 패턴 구현
// singletonBasic.js

let instance = null;

function Singleton(data = 'Initial data') {
  if (instance) {
    return instance;
  }

  this.data = data;
  instance = this;
}

Singleton.prototype.getData = function() {
  return this.data;
}

Singleton.prototype.setData = function(data) {
  this.data = data;
}

export default Singleton;
  • 사용 예시
import Singleton from "./singletonBasic.js"

// Singleton 인스턴스를 
const singleton = new Singleton('First data');

console.log(singleton.getData())  // "First data"

singleton.setData("Updated data");
console.log(singelton.getData())  // "Updated data"

const anotherSingleton = new Singleton("Another data")

console.log(anotherSingleton === singleton) // true
console.log(anotherSingleton, " ---- ", singleton) 
// "Updated data ---- Updated data"

🔹 즉시 실행 함수

  • Singleton 안에서 SingletonClass 라는 함수를 정의하고, 이를 반환
  • Singleton이라는 변수에 SingletonClass라는 인스턴스를 생성하는 함수를 저장한 것
  • SingletonClass 함수를 내부에 캡슐화 했다는 뜻
  • SingletonClass 자체는 외부에서 직접 접근 할 수 없고 Singleton을 통해서만 인스턴스를 생성하거나 사용할 수 있다는 뜻
// Singleton.js

let Singleton = (function() {
  let instance = null;

  function SingletonClass(data = 'Initial data') {
    if (instance) {
      return instance;
    }

    this.data = data;
    instance = this;
  }

  SingletonClass.prototype.getData = function() {
    return this.data;
  }

  SingletonClass.prototype.setData = function(data) {
    this.data = data;
  }

  return SingletonClass;
})();

export default Singleton;
  • 사용 예
import Singleton from './Singleton.js';

let singleton = new Singleton('First data');
console.log(singleton.getData()); // 'First data'

singleton.setData('Updated data');
console.log(singleton.getData()); // 'Updated data'

let anotherSingleton = new Singleton();

console.log(anotherSingleton.getData()); // 'Updated data'
console.log(singleton === anotherSingleton); // true
728x90
반응형
LIST

'Javascript > 자바스크립트 패턴' 카테고리의 다른 글

네임스페이스 패턴  (0) 2024.07.03
팩토리 패턴  (0) 2024.07.03
메모이제이션 패턴  (1) 2024.07.03
고차함수 / 커링 / 부분적용함수  (0) 2024.07.03
클로저  (2) 2024.07.03