Singleton

  • ์ •์˜

    • ํ•˜๋‚˜์˜ ํด๋ž˜์Šค๊ฐ€ ์˜ค์ง ๋‹จ์ผ ์ธ์Šคํ„ด์Šค๋งŒ ๊ฐ€์ง€๋Š” ๊ฒฝ์šฐ

    • ์–ดํ”Œ๋ฆฌ์ผ€์ด์…˜ ๋‚ด์—์„œ ์ „์—ญ์ ์œผ๋กœ ์ ‘๊ทผ์ด ๊ฐ€๋Šฅํ•˜๋‹ค.

    • ์–ด๋–ค ํด๋ž˜์Šค๊ฐ€ ์ตœ์ดˆ ํ•œ๋ฒˆ๋งŒ ๋ฉ”๋ชจ๋ฆฌ์— ํ• ๋‹น(static) ํ•˜๊ณ , ๊ทธ ๋ฉ”๋ชจ๋ฆฌ์— ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ค์–ด ์‚ฌ์šฉํ•˜๋Š” ํŒจํ„ด.

  • ๊ตฌํ˜„ (์•„๋ž˜ ์˜ˆ ๊ฐ™์ด ๋ณด๊ธฐ!)

    • ์ƒ์„ฑ๋œ singleton object๋ฅผ ์ €์žฅํ•  ์ˆ˜ ์žˆ๋Š” ์ž์‹ ๊ณผ ๊ฐ™์€ ํƒ€์ž…์˜ static field์ •์˜

    • ๋ชจ๋“  ์ดˆ๊ธฐํ™” ์ฝ”๋“œ๋ฅผ ์บก์Šํ™” (private or protected constructor)

    • ์ธ์Šคํ„ด์Šค์— ๋Œ€ํ•œ ์—‘์„ธ์Šค๋ฅผ ์ œ๊ณตํ•˜๋Š” public static member function (public getter, ex: getInstance() )

      • ์ด ๋ฉ”์†Œ๋“œ๊ฐ€ ํ˜ธ์ถœ๋˜๋Š” ์‹œ์ ์—์„œ ํ•œ๋ฒˆ๋งŒ ์˜ค๋ธŒ์ ํŠธ๊ฐ€ ๋งŒ๋“ค์–ด์ง€๊ฒŒ ํ•œ๋‹ค.

      • ์ƒ์„ฑ๋œ ์˜ค๋ธŒ์ ํŠธ๋Š” static field์— ์ €์žฅ ํ•˜๊ฑฐ๋‚˜, static field์˜ ์ดˆ๊ธฐ๊ฐ’์œผ๋กœ ์˜ค๋ธŒ์ ํŠธ๋ฅผ ๋ฏธ๋ฆฌ ๋งŒ๋“ค์–ด ๋‘˜ ์ˆ˜ ๋„ ์žˆ๋‹ค.

      • instance์— ๋Œ€ํ•œ ์ ‘๊ทผ ์ œ๊ณต.

    • ํ•œ๋ฒˆ singleton object๋ฅผ ๋งŒ๋“ค๊ณ  ๋‚œ ํ›„์—๋Š” ์ ‘๊ทผ์ž ํ•จ์ˆ˜(getter) ๋ฅผ ํ†ตํ•ด ์ด๋ฏธ ๋งŒ๋“ค์–ด์ ธ static field์— ์ €์žฅํ•ด๋‘” ์˜ค๋ธŒ์ ํŠธ๋ฅผ ๋„˜๊ฒจ์ค€๋‹ค.

  • ์˜ˆ

    public class Singleton{
        //static field
        private static Singleton instance;
    
        //private(protected) constructor: class ๋ฐ–์—์„œ๋Š” object ์ƒ์„ฑ X.
        private Singleton(){...}
    
        //static member function (static factory method)
        //synchronized: thread์—์„œ ๋™์‹œ์ ‘๊ทผ์— ๋Œ€ํ•œ ๋ฌธ์ œ ํ•ด๊ฒฐ (์„ฑ๋Šฅ ์ €ํ•˜ ์›์ธ)
        public static synchronized Singleton getInstance(){
            //lazy init
            if(instance == null) instance = new SingleTon(?);
            return instance;
        }
    
    }
  • ๋ฌธ์ œ์ (ํ•œ๊ณ„)

    • ์ „์—ญ ์ƒํƒœ๋ฅผ ๋งŒ๋“ ๋‹ค.

      • static method๋กœ ์‰ฝ๊ฒŒ ์ ‘๊ทผ ๊ฐ€๋Šฅ

      • ์•„๋ฌด ๊ฐ์ฒด๋‚˜ ์ž์œ ๋กญ๊ฒŒ ์ ‘๊ทผํ•˜๊ณ  ์ˆ˜์ •ํ•˜๊ณ  ๊ณต์œ  ๊ฐ€๋Šฅํ•œ ์ „์—ญ์ƒํƒœ

    • private ์ƒ์„ฑ์ž๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ์–ด์„œ, ์ƒ์† ๋ถˆ๊ฐ€

      • ๊ฐ์ฒด์ง€ํ–ฅ์˜ ์žฅ์ ์ธ ์ƒ์†, ๋‹คํ˜•์„ฑ ์ ์šฉ ๋ถˆ๊ฐ€

    • ํ…Œ์ŠคํŠธ ํ•˜๊ธฐ ์–ด๋ ต๋‹ค.

    • ์„œ๋ฒ„ ํ™˜๊ฒฝ์—์„œ ์‹ฑ๊ธ€ํ†ค์ด ํ•˜๋‚˜๋งŒ ๋งŒ๋“ค์–ด์ง€๋Š” ๊ฒƒ์„ ๋ณด์žฅ ํ•  ์ˆ˜ ์—†๋‹ค.

  • 3๊ฐ€์ง€ ํ•„์ˆ˜ ์ค‘์ด‰ ์š”๊ฑด

    • ๋‹จ์ผ ์ธ์Šคํ„ด์Šค์˜ ์†Œ์œ ๊ถŒ์„ ํ•ฉ๋ฆฌ์ ์œผ๋กœ ํ• ๋‹น ๊ฐ€๋Šฅํ•ด์•ผํ•จ.

    • lazy initialize

    • global access ๋‹ฌ๋ฆฌ ์ œ๊ณต๋˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ.

  • ์žฅ์ 

    • ํ•œ ๋ฒˆ์˜ ๊ฐ์ฒด ์ƒ์„ฑ์œผ๋กœ ์žฌ์‚ฌ์šฉ์ด ๊ฐ€๋Šฅํ•˜๋ฏ€๋กœ, ๋ฉ”๋ชจ๋ฆฌ ๋‚ญ๋น„ ๋ฐฉ์ง€.

    • ํ•œ ๋ฒˆ ์ƒ์„ฑํ•œ ๊ฐ์ฒด๋Š” ๋ฌด์กฐ๊ฑด ํ•œ ๋ฒˆ ์ƒ์„ฑ์œผ๋กœ ์ „์—ญ์„ฑ์„ ๋„๋ฉฐ, ๋‹ค๋ฅธ ๊ฐ์ฒด์™€ ๊ณต์œ ๊ฐ€ ๊ฐ€๋Šฅ.

[์ฐธ๊ณ ]

https://elfinlas.github.io/2019/09/23/java-singleton/

https://blog.seotory.com/post/2016/03/java-singleton-pattern

https://jeong-pro.tistory.com/86

์ฑ… - ํ† ๋น„์˜ ์Šคํ”„๋ง

Last updated