Singleton

์‹ฑ๊ธ€ํ†ค ํŒจํ„ด์€ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ๋‚ด์—์„œ ๋‹จ ํ•˜๋‚˜์˜ ์ธ์Šคํ„ด์Šค๋งŒ ์ƒ์„ฑ๋˜์–ด ๊ณต์œ ๋˜์–ด์•ผ ํ•  ๋•Œ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค. ๋Œ€ํ‘œ์ ์ธ ์˜ˆ๋กœ ๋กœ๊น…(Logger)์ด๋‚˜ ์Šคํ”„๋ง๋นˆ์ด ์žˆ์Šต๋‹ˆ๋‹ค.


Default Singleton (Eager Initialization)

ํด๋ž˜์Šค๊ฐ€ ๋กœ๋”ฉ๋  ๋•Œ ๋ฏธ๋ฆฌ ์ธ์Šคํ„ด์Šค๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.

  • ์žฅ์ : ๊ตฌํ˜„์ด ๊ฐ„๋‹จํ•˜๋ฉฐ ๋ฉ€ํ‹ฐ์Šค๋ ˆ๋“œ ํ™˜๊ฒฝ์—์„œ๋„ ์•ˆ์ „ํ•ฉ๋‹ˆ๋‹ค.

  • ๋‹จ์ : ์‚ฌ์šฉํ•˜์ง€ ์•Š๋”๋ผ๋„ ์ธ์Šคํ„ด์Šค๊ฐ€ ์ƒ์„ฑ๋˜์–ด ๋ฉ”๋ชจ๋ฆฌ ๋‚ญ๋น„๊ฐ€ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

public class EagerSingleton {
    private static final EagerSingleton instance = new EagerSingleton();

    private EagerSingleton() { }

    public static EagerSingleton getInstance() {
        return instance;
    }
}

Instance Field ๋ฐฉ์‹

ํด๋ž˜์Šค ๋กœ๋”ฉ ์‹œ์ ์— ์ธ์Šคํ„ด์Šค๊ฐ€ ์ƒ์„ฑ๋˜๋ฏ€๋กœ Default ๋ฐฉ์‹๊ณผ ๋™์ผํ•˜๊ฒŒ ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉ์ด ๋ถˆํ•„์š”ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

public class InstanceFieldSingleton {
    private static InstanceFieldSingleton instance = new InstanceFieldSingleton();

    private InstanceFieldSingleton() { }

    public static InstanceFieldSingleton getInstance() {
        return instance;
    }
}

Lazy Loading

ํด๋ž˜์Šค๊ฐ€ ๋กœ๋”ฉ๋  ๋•Œ ์ธ์Šคํ„ด์Šค๋ฅผ ์ƒ์„ฑํ•˜์ง€ ์•Š๊ณ , ์‹ค์ œ๋กœ ํ•„์š”ํ•  ๋•Œ ์ƒ์„ฑํ•˜์—ฌ ๋ฉ”๋ชจ๋ฆฌ ๋‚ญ๋น„๋ฅผ ์ค„์ž…๋‹ˆ๋‹ค.

  • ์žฅ์ : ์‹ค์ œ ์‚ฌ์šฉ ์‹œ์ ์— ์ธ์Šคํ„ด์Šค๋ฅผ ์ƒ์„ฑํ•˜๋ฏ€๋กœ ๋ฉ”๋ชจ๋ฆฌ ํšจ์œจ์ ์ž…๋‹ˆ๋‹ค.

  • ๋‹จ์ : ๋ฉ€ํ‹ฐ์Šค๋ ˆ๋“œ ํ™˜๊ฒฝ์—์„œ ๋™๊ธฐํ™”(synchronized) ์ฒ˜๋ฆฌ๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค.

public class LazySingleton {
    private static LazySingleton instance;

    private LazySingleton() { }

    public static synchronized LazySingleton getInstance() {
        if (instance == null) {
            instance = new LazySingleton();
        }
        return instance;
    }
}

Standard / Joshua ๋ธ”๋ก ๋ฐฉ์‹

Joshua Bloch๊ฐ€ ์ œ์•ˆํ•œ ๋ฐฉ์‹์œผ๋กœ, Bill Pugh์˜ ๋‚ด๋ถ€ ์ •์  ํด๋ž˜์Šค ๋ฐฉ์‹์„ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค. ์ด ๋ฐฉ๋ฒ•์€ ํด๋ž˜์Šค ๋กœ๋”ฉ ์‹œ์ ๊ณผ ์‹ค์ œ ์‚ฌ์šฉ ์‹œ์ ์˜ ์žฅ์ ์„ ๋ชจ๋‘ ์ทจํ•˜๋ฉฐ, ๋ฉ€ํ‹ฐ์Šค๋ ˆ๋“œ ํ™˜๊ฒฝ์—์„œ ์•ˆ์ „ํ•ฉ๋‹ˆ๋‹ค.

public class StandardSingleton {
    private StandardSingleton() { }

    private static class SingletonHelper {
        private static final StandardSingleton INSTANCE = new StandardSingleton();
    }

    public static StandardSingleton getInstance() {
        return SingletonHelper.INSTANCE;
    }
}
  • Default/Instance Field ๋ฐฉ์‹: ํด๋ž˜์Šค ๋กœ๋”ฉ ์‹œ์ ์— ์ธ์Šคํ„ด์Šค๊ฐ€ ์ƒ์„ฑ๋˜์–ด ๊ฐ„๋‹จํ•˜์ง€๋งŒ, ์‚ฌ์šฉํ•˜์ง€ ์•Š์„ ๊ฒฝ์šฐ์—๋„ ์ธ์Šคํ„ด์Šค๊ฐ€ ์ƒ์„ฑ๋ฉ๋‹ˆ๋‹ค.

  • Lazy Loading ๋ฐฉ์‹: ์ธ์Šคํ„ด์Šค๊ฐ€ ์‹ค์ œ๋กœ ํ•„์š”ํ•  ๋•Œ ์ƒ์„ฑํ•˜์—ฌ ๋ฉ”๋ชจ๋ฆฌ๋ฅผ ํšจ์œจ์ ์œผ๋กœ ์‚ฌ์šฉํ•˜์ง€๋งŒ, ๋™๊ธฐํ™” ๋น„์šฉ์ด ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

  • Standard/Joshua ๋ฐฉ์‹: Bill Pugh์˜ ๋‚ด๋ถ€ ํด๋ž˜์Šค ๋ฐฉ์‹์„ ํ™œ์šฉํ•ด ์Šค๋ ˆ๋“œ ์•ˆ์ „ํ•˜๋ฉด์„œ๋„ ์ง€์—ฐ ์ดˆ๊ธฐํ™”๋ฅผ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

Last updated