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

reviews/Effective JAVA

003. private ์ƒ์„ฑ์ž๋‚˜ ์—ด๊ฑฐ ํƒ€์ž…์œผ๋กœ ์‹ฑ๊ธ€ํ„ด์ž„์„ ๋ณด์ฆํ•˜๋ผ

๐Ÿ‘‰ ์‹ฑ๊ธ€ํ„ด(Singleton)

์ธ์Šคํ„ด์Šค๋ฅผ ์˜ค์ง ํ•˜๋‚˜๋งŒ ์ƒ์„ฑํ•  ์ˆ˜ ์žˆ๋Š” ํด๋ž˜์Šค

ํ•จ์ˆ˜์™€ ๊ฐ™์€ ๋ฌด์ƒํƒœ(stateless) ๊ฐ์ฒด๋‚˜ ์„ค๊ณ„์ƒ ์œ ์ผํ•ด์•ผ ํ•˜๋Š” ์‹œ์Šคํ…œ ์ปดํฌ๋„ŒํŠธ ๋“ฑ

๋‹จ์ 

  • ํด๋ผ์ด์–ธํŠธ ํ…Œ์ŠคํŠธ๊ฐ€ ์šฉ์ดํ•˜์ง€ ์•Š๋‹ค. ํด๋ž˜์Šค๋ฅผ ์‹ฑ๊ธ€ํ„ด์œผ๋กœ ๋งŒ๋“ค๋ฉด ํƒ€์ž…์„ ์ธํ„ฐํŽ˜์ด์Šค๋กœ ๋งŒ๋“ค๊ณ  ๊ทธ ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ๊ตฌํ˜„ํ•ด์„œ ๋งŒ๋“  ์‹ฑ๊ธ€ํ„ด์ด ์•„๋‹Œ ๊ฒฝ์šฐ ์‹ฑ๊ธ€ํ„ด ์ธ์Šคํ„ด์Šค๋ฅผ ๊ฐ€์งœ(mock) ๊ตฌํ˜„์œผ๋กœ ๋Œ€์ฒดํ•  ์ˆ˜ ์—†๊ธฐ ๋•Œ๋ฌธ

๐Ÿ‘‰ ์‹ฑ๊ธ€ํ„ด์„ ์ž…๋ ฅํ•˜๋Š” ๋ฐฉ์‹

๋‘ ๋ฐฉ์‹ ๋ชจ๋‘ ์ƒ์„ฑ์ž๋Š” private์œผ๋กœ ๊ฐ์ถฐ๋‘๊ณ , ์œ ์ผํ•œ ์ธ์Šคํ„ด์Šค์— ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋Š” ์ˆ˜๋‹จ์œผ๋กœ public static ๋ฉค๋ฒ„๋ฅผ ๋งˆ๋ จํ•œ๋‹ค.

♦๏ธŽ public static final ํ•„๋“œ ๋ฐฉ์‹์˜ ์‹ฑ๊ธ€ํ„ด

private ์ƒ์„ฑ์ž๋Š” public static final ํ•„๋“œ์ธ Elvis.INSTANCE๋ฅผ ์ดˆ๊ธฐํ™” ํ•  ๋•Œ ๋”ฑ ํ•œ ๋ฒˆ ํ˜ธ์ถœ๋œ๋‹ค.

์ƒ์„ฑ์ž๊ฐ€ private์ด๋ฏ€๋กœ ์ด ์ธ์Šคํ„ด์Šค๊ฐ€ ์ „์ฒด ์‹œ์Šคํ…œ์—์„œ ํ•˜๋‚˜๋ฟ์ž„์ด ๋ณด์žฅ๋œ๋‹ค.

/** PublicStaticFinal.java */
public class Elvis {
    public static final Elvis INSTANCE = new Elvis();
    private Elvis() {}
    public void leaveTheBuilding() {}
}

์žฅ์ 

  • ํ•ด๋‹น ํด๋ž˜์Šค๊ฐ€ ์‹ฑ๊ธ€ํ„ด์ž„์ด API์— ๋ช…๋ฐฑํžˆ ๋“œ๋Ÿฌ๋‚œ๋‹ค.
  • ๊ฐ„๊ฒฐํ•˜๋‹ค.

♦๏ธŽ ์ •์  ํŒฉํ„ฐ๋ฆฌ ๋ฐฉ์‹

INSTANCE๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” public static ๋ฉ”์„œ๋“œ getInstance()๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค.

์•„๋ž˜์˜ ์žฅ์ ๋“ค์ด ํ•„์š”ํ•œ ๊ฒฝ์šฐ๊ฐ€ ์•„๋‹ˆ๋ผ๋ฉด public ํ•„๋“œ ๋ฐฉ์‹์ด ๋‚ซ๋‹ค...

/** StaticFactory.java */
public class Elvis2 {
    private static final Elvis2 INSTANCE = new Elvis2();
    private Elvis2() {}
    public static Elvis2 getInstance() { return INSTANCE; }
    public void leaveTheBuilding() {}
}

์žฅ์ 

  • ๋งˆ์Œ์ด ๋ฐ”๋€Œ๋ฉด API๋ฅผ ๋ฐ”๊พธ์ง€ ์•Š๊ณ ๋„ ์‹ฑ๊ธ€ํ„ด์ด ์•„๋‹ˆ๊ฒŒ ๋ณ€๊ฒฝํ•  ์ˆ˜ ์žˆ๋‹ค.
  • ์›ํ•œ๋‹ค๋ฉด ์ •์  ํŒฉํ„ฐ๋ฆฌ๋ฅผ ์ œ๋„ค๋ฆญ ์‹ฑ๊ธ€ํ„ด ํŒฉํ„ฐ๋ฆฌ๋กœ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค.
  • ์ •์  ํŒฉํ„ฐ๋ฆฌ์˜ ๋ฉ”์„œ๋“œ ์ฐธ์กฐ๋ฅผ ๊ณต๊ธ‰์ž๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.
  • ex) Elvis::getInstance๋ฅผ Supplier<Elvis>

♦๏ธŽ ๋ฆฌํ”Œ๋ ‰์…˜ API

๊ถŒํ•œ์ด ์žˆ๋Š” ํด๋ผ์ด์–ธํŠธ๋Š” ๋ฆฌํ”Œ๋ ‰์…˜ API์ธ AccessibleObject.setAccessible์„ ์‚ฌ์šฉํ•ด private ์ƒ์„ฑ์ž๋ฅผ ํ˜ธ์ถœํ•  ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ ๋ฐฉ์–ดํ•˜๊ธฐ ์œ„ํ•œ ์ฝ”๋“œ๊ฐ€ ํ•„์š”ํ•˜๋‹ค.

๊ฒฐ๋ก 

enum ๋ฐฉ์‹์ด ์งฑ์ด๋‹ค. ??

๋ฐ˜์‘ํ˜•