Java

[Effective Java] ์•„์ดํ…œ 36. ๋น„ํŠธ ํ•„๋“œ ๋Œ€์‹  EnumSet์„ ์‚ฌ์šฉํ•˜๋ผ.

quedevel 2023. 3. 21. 10:37
728x90
๋ฐ˜์‘ํ˜•

๐ŸŽฏ ์•„์ดํ…œ 36. ๋น„ํŠธ ํ•„๋“œ ๋Œ€์‹  EnumSet์„ ์‚ฌ์šฉํ•˜๋ผ.

  • ๋น„ํŠธ ํ•„๋“œ ์—ด๊ฑฐ ์ƒ์ˆ˜ - ๊ตฌ๋‹ฅ๋‹ค๋ฆฌ ๊ธฐ๋ฒ•!

    public class Text {
      public static final int STYLE_BOLD          = 1 << 0; // 1
      public static final int STYLE_ITALIC        = 1 << 1; // 2
      public static final int STYLE_UNDERLINE     = 1 << 2; // 4
      public static final int STYLE_STRIKETHROUGH = 1 << 3; // 5
    
      public void applyStyles(int styles){ ... }
    }

    ๋‹ค์Œ๊ณผ ๊ฐ€์€ ์‹์œผ๋กœ ๋น„ํŠธ๋ณ„ OR๋ฅผ ์‚ฌ์šฉํ•ด ์—ฌ๋Ÿฌ ์ƒ์ˆ˜๋ฅผ ํ•˜๋‚˜์˜ ์ง‘ํ•ฉ์œผ๋กœ ๋ชจ์„ ์ˆ˜ ์žˆ์œผ๋ฉฐ, ์ด๋ ‡๊ฒŒ ๋งŒ๋“ค์–ด์ง„ ์ง‘ํ•ฉ์„ ๋น„ํŠธ ํ•„๋“œ๋ผ ํ•œ๋‹ค.

    text.applyStyles(STYLE_BOLD | STYLE_ITALIC);

    ํ•˜์ง€๋งŒ ๋น„ํŠธ ํ•„๋“œ๋Š” ์ •์ˆ˜ ์—ด๊ฑฐ ์ƒ์ˆ˜์˜ ๋‹จ์ ์„ ๊ทธ๋Œ€๋กœ ์ง€๋‹ˆ๋ฉฐ, ์ถ”๊ฐ€๋กœ ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๋ฌธ์ œ๊นŒ์ง€ ์žˆ๋‹ค.

    ๋น„ํŠธ ํ•„๋“œ ๊ฐ’์ด ๊ทธ๋Œ€๋กœ ์ถœ๋ ฅ๋˜๋ฉด ๋‹จ์ˆœํ•œ ์ •์ˆ˜ ์—ด๊ฑฐ ์ƒ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•  ๋•Œ๋ณด๋‹ค ํ•ด์„ํ•˜๊ธฐ๊ฐ€ ์–ด๋ ต๋‹ค.


  • EnumSet - ๋น„ํŠธ ํ•„๋“œ๋ฅผ ๋Œ€์ฒดํ•˜๋Š” ํ˜„๋Œ€์  ๊ธฐ๋ฒ•

    public class Text {
      public enum Style {BOLD, ITALIC, UNDERLINE, STRIKETHROUGH}
    
      // ์–ด๋–ค Set์„ ๋„˜๊ฒจ๋„ ๋˜๋‚˜, EnumSet์ด ๊ฐ€์žฅ ์ข‹๋‹ค.
      public void applyStyles(Set<Style> styles) {
          System.out.printf("Applying styles %s to text%n", Objects.requireNonNull(styles));
      }
    
      // ์‚ฌ์šฉ ์˜ˆ
      public static void main(String[] args) {
          Text text = new Text();
          text.applyStyles(EnumSet.of(Style.BOLD, Style.ITALIC));
      }
    }
  • EnumSet ํด๋ž˜์Šค๊ฐ€ ๋น„ํŠธ ํ•„๋“œ ์ˆ˜์ค€์˜ ๋ช…๋ฃŒํ•จ๊ณผ ์„ฑ๋Šฅ์„ ์ œ๊ณตํ•˜๊ณ  ์—ด๊ฑฐ ํƒ€์ž…์˜ ์žฅ์ ๊นŒ์ง€ ์„ ์‚ฌํ•œ๋‹ค.*


์ฐธ๊ณ  ์ž๋ฃŒ

Joshua Bloch, ใ€ŽEffective Java 3/Eใ€, ๊ฐœ์•ž๋งต์‹œ ์˜ฎ๊น€, ํ”„๋กœ๊ทธ๋ž˜๋ฐ์ธ์‚ฌ์ดํŠธ(2018)
http://www.kyobobook.co.kr/product/detailViewKor.laf?ejkGb=KOR&mallGb=KOR&barcode=9788966262281&orderClick=LEa&Kc=

728x90
๋ฐ˜์‘ํ˜•