๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๊ฐœ๋ฐœ/JAVA

[JAVA] ์‹ฑ๊ธ€ํ†ค ํŒจํ„ด(Singleton Pattern) : ๋ฉ€ํ‹ฐ ์Šค๋ ˆ๋“œ ํ™˜๊ฒฝ์—์„œ์˜ ๋ฌธ์ œ์ 

by ynzu๐Ÿค 2022. 2. 10.
๋ฐ˜์‘ํ˜•

 

์‹ฑ๊ธ€ํ†ค ํŒจํ„ด์ด๋ž€?

ํ•œ๋งˆ๋””๋กœ ์ •์˜ํ•˜์ž๋ฉด '๊ฐ์ฒด๋ฅผ ๋‹จ ํ•˜๋‚˜๋งŒ ์ƒ์„ฑํ•˜๋„๋ก ํ•˜๋Š” ๋””์ž์ธ ํŒจํ„ด'!

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

 

์‹ฑ๊ธ€ํ†ค ํŒจํ„ด์˜ ์˜ˆ์ œ๋ฅผ ๋ณด๋ฉด ์•„๋ž˜์™€ ๊ฐ™์€ ํ˜•ํƒœ๊ฐ€ ๋Œ€๋ถ€๋ถ„์ด๋‹ค.

๋ณธ์ธ๋„ ์‹ฑ๊ธ€ํ†ค ํด๋ž˜์Šค๋ฅผ ์ž‘์„ฑํ•  ๋•Œ ์ด๋ ‡๊ฒŒ ์ž‘์„ฑํ•˜์˜€๋Š”๋ฐ, ์ด๋Ÿฐ ๊ฒฝ์šฐ ๋ฉ€ํ‹ฐ์Šค๋ ˆ๋“œ ํ™˜๊ฒฝ์—์„  ๋‘๊ฐœ ์ด์ƒ์˜ ์Šค๋ ˆ๋“œ๊ฐ€ getInstance()๋ฅผ ํ•˜๊ฒŒ ๋  ๊ฒฝ์šฐ ๋‘๊ฐœ์˜ ์ธ์Šคํ„ด์Šค๊ฐ€ ์ƒ์„ฑ๋˜๋Š” ๋ฌธ์ œ๊ฐ€ ์ƒ๊ธธ ์ˆ˜ ์žˆ๋‹ค. (= ๋™์‹œ์„ฑ ๋ฌธ์ œ, thread unsafe)

public class Singleton {
    private static Singleton singleton = null;

    private Singleton(){}

    public static Singleton getInstance(){
        if(singleton == null){
            singleton = new Singleton();
        }
        return singleton;
    }
}

 

ํ•ด๊ฒฐ ๋ฐฉ๋ฒ•

1.  ์ธ์Šคํ„ด์Šค๋ฅผ ํ˜ธ์ถœํ•  ๋•Œ ์ƒ์„ฑํ•˜์ง€ ์•Š๊ณ , ์ฒ˜์Œ๋ถ€ํ„ฐ ์ƒ์„ฑํ•˜๋Š” ๋ฐฉ๋ฒ•.

์ด๋Ÿฐ ๊ฒฝ์šฐ ๋ถˆํ•„์š”ํ•œ ๊ฒฝ์šฐ์—๋„ ์ธ์Šคํ„ด์Šค๊ฐ€ ์ƒ์„ฑ๋˜๋ฏ€๋กœ ๋ฆฌ์†Œ์Šค๊ฐ€ ๋‚ญ๋น„๋œ๋‹ค.

public class Singleton {
    private static Singleton singleton = new Singleton();

    private Singleton(){}

    public static Singleton getInstance(){
         return new Singleton();
    }
}

 

2. Thread safe Lazy initialization ๋ฐฉ๋ฒ• - synchronized

synchronized ํ‚ค์›Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•ด์„œ getInstance() ๋ฉ”์†Œ๋“œ๋ฅผ ๋™๊ธฐํ™” ์‹œํ‚ด์œผ๋กœ์จ thread-safeํ•˜๊ฒŒ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค.

ํ•˜์ง€๋งŒ ํฐ ์„ฑ๋Šฅ์ €ํ•˜๊ฐ€ ๋ฐœ์ƒํ•˜๋ฏ€๋กœ ๊ถŒ์žฅํ•˜์ง€ ์•Š๋Š” ๋ฐฉ๋ฒ•์ด๋‹ค.

public class Singleton {
    private static Singleton singleton = null;

    private Singleton(){}

    public synchronized static Singleton getInstance(){
        if(singleton == null){
            singleton = new Singleton();
        }
        return singleton;
    }
}

 Double-checked locking์„ ํ†ตํ•ด ์„ฑ๋Šฅ ์ €ํ•˜๋ฅผ ์™„ํ™”์‹œํ‚ค๋Š” ๋ฐฉ๋ฒ•๋„ ์žˆ๋‹ค๋Š”๋ฐ ์™„๋ฒฝํ•œ ๋ฐฉ๋ฒ•์€ ์•„๋‹ˆ๋ผ๊ณ  ํ•œ๋‹ค.  

 

3. Holder initialization ๋ฐฉ๋ฒ• - LazyHolder

๊ฐ€์žฅ ๋งŽ์ด ์‚ฌ์šฉ๋˜๊ณ  ์žˆ๋Š” ํ•ด๊ฒฐ ๋ฐฉ๋ฒ•์œผ๋กœ getInstance()๋ฉ”์„œ๋“œ์—์„œ LazyHolder.INSTANCE๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ์ˆœ๊ฐ„ Class๊ฐ€ ๋กœ๋”ฉ๋˜๋ฉฐ ์ดˆ๊ธฐํ™”๊ฐ€ ์ง„ํ–‰๋˜๊ณ , ์ด ์‹œ์ ์— thread-safe๋ฅผ ๋ณด์žฅํ•œ๋‹ค.

public class Singleton {
    private Singleton(){}

    public static Singleton getInstance(){
        return LazyHolder.INSTANCE;
    }
	
	private static class LazyHolder {
 		public static final Singleton INSTANCE = new Singleton();
    }
}

์ด ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•˜์—ฌ ๋ฉ€ํ‹ฐ ์Šค๋ ˆ๋“œ ํ™˜๊ฒฝ์—์„œ์˜ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ์ ์„ ํ•ด๊ฒฐํ•˜์˜€๋‹ค.

 

 

์ฐธ๊ณ  : https://jeong-pro.tistory.com/86

728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€