Java

[Effective Java] ์•„์ดํ…œ 38. ํ™•์žฅํ•  ์ˆ˜ ์žˆ๋Š” ์—ด๊ฑฐ ํƒ€์ž…์ด ํ•„์š”ํ•˜๋ฉด ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ์‚ฌ์šฉํ•˜๋ผ.

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

๐ŸŽฏ ์•„์ดํ…œ 38. ํ™•์žฅํ•  ์ˆ˜ ์žˆ๋Š” ์—ด๊ฑฐ ํƒ€์ž…์ด ํ•„์š”ํ•˜๋ฉด ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ์‚ฌ์šฉํ•˜๋ผ.

  • ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ์ด์šฉํ•ด ํ™•์žฅ ๊ฐ€๋Šฅ ์—ด๊ฑฐ ํƒ€์ž…์„ ํ‰๋‚ด ๋ƒˆ๋‹ค.

    public interface Operation {
      double apply(double x, double y);
    }
    public enum BasicOperation implements Operation{
      PLUS("+") {
          public double apply(double x, double y) { return x + y; }
      },
      MINUS("-") {
          public double apply(double x, double y) { return x - y; }
      },
      TIMES("*") {
          public double apply(double x, double y) { return x * y; }
      },
      DIVIDE("/") {
          public double apply(double x, double y) { return x / y; }
      };
    
      private final String symbol;
    
      BasicOperation(String symbol) {
          this.symbol = symbol;
      }
    
      @Override public String toString() {
          return symbol;
      }
    }

    ์—ด๊ฑฐ ํƒ€์ž…์ด ๊ทธ ์ธํ„ฐํŽ˜์ด์Šค์˜ ํ‘œ์ค€ ๊ตฌํ˜„์ฒด ์—ญํ• ์„ ํ•œ๋‹ค. ์—ด๊ฑฐ ํƒ€์ž…์ธ BasicOperation์€ ํ™•์žฅํ•  ์ˆ˜ ์—†์ง€๋งŒ

    ์ธํ„ฐํŽ˜์ด์Šค์ธ Operation์€ ํ™•์žฅํ•  ์ˆ˜ ์žˆ๊ณ , ์ด ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ์—ฐ์‚ฐ์˜ ํƒ€์ž…์œผ๋กœ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค.


  • ํ™•์žฅ ๊ฐ€๋Šฅ ์—ด๊ฑฐ ํƒ€์ž…
    public enum ExtendedOperation implements Operation{
      EXP("^") {
          public double apply(double x, double y) {
              return Math.pow(x, y);
          }
      },
      REMAINDER("%") {
          public double apply(double x, double y) {
              return x % y;
          }
      };
      private final String symbol;
      ExtendedOperation(String symbol) {
          this.symbol = symbol;
      }
      @Override public String toString() {
          return symbol;
      }
    }
    ์—ด๊ฑฐ ํƒ€์ž… ์ž์ฒด๋Š” ํ™•์žฅํ•  ์ˆ˜ ์—†์ง€๋งŒ, ์ธํ„ฐํŽ˜์ด์Šค์™€ ๊ทธ ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ๊ตฌํ˜„ํ•˜๋Š” ๊ธฐ๋ณธ ์—ด๊ฑฐ ํƒ€์ž…์„ ํ•จ๊ป˜ ์‚ฌ์šฉํ•ด ๊ฐ™์€ ํšจ๊ณผ๋ฅผ ๋‚ผ ์ˆ˜ ์žˆ๋‹ค.

    ์ด๋ ‡๊ฒŒ ํ•˜๋ฉด ํด๋ผ์ด์–ธํŠธ๋Š” ์ด ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ๊ตฌํ˜„ํ•ด ์ž์‹ ๋งŒ์˜ ์—ด๊ฑฐ ํƒ€์ž…์„ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค.

์ฐธ๊ณ  ์ž๋ฃŒ

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
๋ฐ˜์‘ํ˜•