Design Pattern

Singleton Pattern

eddie0329 2020. 10. 5. 17:24
λ°˜μ‘ν˜•

πŸ“Œ λͺ©μ°¨

  • Introduction
  • Singleton νŒ¨ν„΄μ΄λž€?
  • Singleton νŒ¨ν„΄ κ΅¬ν˜„
  • Conclusion
  • Reference

πŸ“Œ Introduction

μ•ˆλ…•ν•˜μ„Έμš” 이번 ν¬μŠ€νŒ…μ—μ„œλŠ” design pattern쀑 singleton νŒ¨ν„΄μ— λŒ€ν•΄μ„œ λ°°μ›Œλ³΄κ² μŠ΅λ‹ˆλ‹€!

πŸ“Œ Singleton νŒ¨ν„΄μ΄λž€?

μ΄λ¦„μ—μ„œ single이 λ“€μ–΄κ°€λŠ” κ²ƒμœΌλ‘œ μœ μΆ”ν•  수 μžˆλ“―μ΄ 전체 μ‹œμŠ€ν…œμ—μ„œμ˜ ν•˜λ‚˜μ˜ μΈμŠ€ν„΄μŠ€λ₯Ό μ‘΄μž¬ν•˜λ„λ‘ 보μž₯ν•˜λŠ” 객체 μƒμ„±νŒ¨ν„΄μž…λ‹ˆλ‹€. λ”°λΌμ„œ, 객체 λ¦¬ν„°λŸ΄λ„ λͺ¨λ‘ 싱글톀 νŒ¨ν„΄μ΄λΌκ³  ν•  수 μžˆμŠ΅λ‹ˆλ‹€. ν•˜μ§€λ§Œ λͺ¨λ“  속성이 λ‹€ κ³΅κ°œκ°€ λ˜μ–΄μžˆκΈ°μ— λΉ„κ³΅κ°œλ₯Ό λ§Œλ“€λ•Œ μ œλŒ€λ‘œ 된 singleton νŒ¨ν„΄ μž…λ‹ˆλ‹€.

πŸ“Œ Singleton νŒ¨ν„΄ κ΅¬ν˜„

Singleton은 객체 λ¦¬ν„°λŸ΄ + ν΄λ‘œμ €λ‘œ κ΅¬ν˜„ν•  수 μžˆμŠ΅λ‹ˆλ‹€. λ‹€μŒ μ½”λ“œλ₯Ό λ΄μ£Όμ„Έμš”.

const singleton = (() => {
  let instance;
  const a = 'hello';
  const initiate = () => ({
    a: a,
    b: () => {
      console.log(a);
    }
  });
  return {
    getInstance: (name) => {
      if (!instance) {
        instance = initiate();
      }
      return instance;
    }
  }
})();

const first = singleton.getInstance();
const second = singleton.getInstance();
console.log(first === second); // true
console.log(first.a); // hello
first.b(); // hello

μ½”λ“œλ₯Ό μ‚΄νŽ΄λ³΄μžλ©΄ singletonμ΄λΌλŠ” λ³€μˆ˜λŠ” μ¦‰μ‹œ μ‹€ν–‰ ν•¨μˆ˜(IIFE)둜써 λ°”λ‘œ instanceλ₯Ό μƒμ„±ν•˜κ²Œ λ©λ‹ˆλ‹€. κ·Έλž˜μ„œ first === secondκ°€ 참이 되게 λ©λ‹ˆλ‹€.

πŸ“Œ Conclusion

JavascriptλŠ” 클래슀 기반의 μ–Έμ–΄κ°€ μ•„λ‹ˆλΌ κ·Έλ ‡κ²Œ μœ μš©ν•œ νŽΈμ€ μ•„λ‹™λ‹ˆλ‹€. κ·ΈλŸΌμ—λ„ ν•΄λ‹Ή νŒ¨ν„΄μ„ μ•„λŠ” 것과 λͺ¨λ₯΄λŠ” 것은 μ²œμ§€μ°¨μ΄ 라고 μƒκ°ν•©λ‹ˆλ‹€. 그럼 λ‹€μŒ μ‹œκ°„μ— λ§Œλ‚˜μš”~!

πŸ“Œ Reference

λ°˜μ‘ν˜•