Skip to content

Latest commit

ย 

History

History
80 lines (54 loc) ยท 2.22 KB

singleton-java.md

File metadata and controls

80 lines (54 loc) ยท 2.22 KB

์‹ฑ๊ธ€ํ†ค (Singleton) Java ๊ตฌํ˜„ ๋ฐฉ๋ฒ•

์ž‘์„ฑ์ž : ์„œ๊ทธ๋ฆผ

์‹ฑ๊ธ€ํ†ค ๋””์ž์ธ ํŒจํ„ด์— ๋Œ€ํ•œ ์ž์„ธํ•œ ์„ค๋ช…์€ ์‹ฑ๊ธ€ํ†ค (Singleton) ๋ฌธ์„œ๋ฅผ ์ฐธ๊ณ ํ•˜์„ธ์š”. ์—ฌ๊ธฐ์„œ๋Š” ์‹ฑ๊ธ€ํ†ค ๋””์ž์ธ ํŒจํ„ด์˜ Java ๊ตฌํ˜„ ๋ฐฉ๋ฒ•์„ ์ •๋ฆฌํ•ฉ๋‹ˆ๋‹ค.

private ์ƒ์„ฑ์ž

Java์˜ ์‹ฑ๊ธ€ํ†ค ๊ตฌํ˜„์€ ์ƒ์„ฑ์ž์— ๋Œ€ํ•œ ์ดํ•ด๋กœ๋ถ€ํ„ฐ ์‹œ์ž‘ํ•œ๋‹ค. ์ƒ์„ฑ์ž๋ฅผ public์œผ๋กœ ๋‘”๋‹ค๋ฉด ๋ˆ„๊ตฌ๋‚˜ ์ ‘๊ทผํ•˜์—ฌ ๊ฐ์ฒด ์ƒ์„ฑ์ด ๊ฐ€๋Šฅํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์˜ค์ง ํ•˜๋‚˜์˜ ๊ฐ์ฒด ์ƒ์„ฑ์— ๋Œ€ํ•œ ์ œ์•ฝ์„ ๊ฑธ ์ˆ˜ ์—†๋‹ค. ๋”ฐ๋ผ์„œ ์ƒ์„ฑ์ž๋ฅผ private์œผ๋กœ ๋‘๊ณ , ์ƒ์„ฑ๋œ ๊ฐ์ฒด๋Š” static ๋ณ€์ˆ˜๋กœ ๊ด€๋ฆฌ, ๊ฐ์ฒด ์ ‘๊ทผ์— ๋Œ€ํ•œ ๋ถ€๋ถ„์€ ๋ณ„๋„์˜ publicํ•œ method๋ฅผ ๋‘ฌ์„œ ์‹ฑ๊ธ€ํ†ค ๋””์ž์ธ ํŒจํ„ด์„ ๊ตฌํ˜„ํ•œ๋‹ค.

class ClassName {
    private ClassName() {}
}

๊ฐ์ฒด ์ƒ์„ฑ์˜ 3๊ฐ€์ง€ ๋ฐฉ๋ฒ•

์ƒ์„ฑ์ž๋ฅผ private์œผ๋กœ ๋’€์„ ๋•Œ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜๋Š” ๋ฐฉ๋ฒ•์€ ๋‹ค์Œ์˜ 3๊ฐ€์ง€ ๊ฒฝ์šฐ๊ฐ€ ์žˆ์„ ์ˆ˜ ์žˆ๋‹ค.

getInstance

์ฝ”๋“œ๊ฐ€ ์ง๊ด€์ ์ด๋‚˜ if ์กฐ๊ฑด ์ฒดํฌ๊ฐ€ ๋ฒˆ๊ฑฐ๋กญ๋‹ค๋Š” ๋‹จ์ ์ด ์žˆ๋‹ค.

class ClassName {
    private ClassName() {}

    static ClassName className;

    public static ClassName getInstance() {
        if (className == null) className = new ClassName();
        return className; // ๊ฐ์ฒด ์ ‘๊ทผ
    }
}

static block

๊ฐ€์žฅ ๊ฐ„๊ฒฐํ•œ ๋ฐฉ๋ฒ•์ด๋‹ค.

class ClassName {
    private ClassName() {}
    
    private static ClassName className;
    static { className = new ClassName(); }
}

member ๋ณ€์ˆ˜ ์„ ์–ธ ์‹œ ์ƒ์„ฑ

์ด ๋ฐฉ๋ฒ•์€ ๋˜๋„๋ก ์ง€์–‘ํ•˜๋Š” ๋ฐฉ๋ฒ•์ด๋‹ค.

class ClassName {
    private ClassName() {}
    
    private static ClassName className = new ClassName();
}

๊ฐ์ฒด ์ ‘๊ทผ

์ž๊ธฐ ์ž์‹ ์„ returnํ•˜๋Š” public static method๋ฅผ ๊ตฌํ˜„ํ•œ๋‹ค. static ๋ณ€์ˆ˜์—๋Š” static ๋ผ๋ฆฌ๋งŒ ์ ‘๊ทผ์ด ๊ฐ€๋Šฅํ•˜๊ธฐ ๋•Œ๋ฌธ์— static์œผ๋กœ ์„ ์–ธํ•ด์•ผ ํ•œ๋‹ค.

class ClassName {
    private ClassName() {}

    private static ClassName className;
    static { className = new ClassName(); }
    
    public static ClassName getInstance() {
        return className;
    }
}

Singleton Java ์ „์ฒด ๊ตฌํ˜„ โ–ถ๏ธ SingletonTest.java