Java

[Effective Java] ์•„์ดํ…œ 23. ํƒœ๊ทธ ๋‹ฌ๋ฆฐ ํด๋ž˜์Šค๋ณด๋‹ค๋Š” ํด๋ž˜์Šค ๊ณ„์ธต๊ตฌ์กฐ๋ฅผ ํ™œ์šฉํ•˜๋ผ.

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

๐ŸŽฏ ์•„์ดํ…œ 23. ํƒœ๊ทธ ๋‹ฌ๋ฆฐ ํด๋ž˜์Šค๋ณด๋‹ค๋Š” ํด๋ž˜์Šค ๊ณ„์ธต๊ตฌ์กฐ๋ฅผ ํ™œ์šฉํ•˜๋ผ.

  • ํƒœ๊ทธ ๋‹ฌ๋ฆฐ ํด๋ž˜์Šค - ํด๋ž˜์Šค ๊ณ„์ธต๊ตฌ์กฐ๋ณด๋‹ค ํ›จ์”ฌ ๋‚˜์˜๋‹ค!

    public class Figure {
      enum Shape { RECTANGLE, CIRCLE };
    
      // ํƒœ๊ทธ ํ•„๋“œ - ํ˜„์žฌ ๋ชจ์–‘์„ ๋‚˜ํƒ€๋‚ธ๋‹ค.
      final Shape shape;
    
      // ๋‹ค์Œ ํ•„๋“œ๋“ค์€ ๋ชจ์–‘์ด ์‚ฌ๊ฐํ˜•(RECTANGLE)์ผ ๋•Œ๋งŒ ์“ฐ์ธ๋‹ค.
      double length;
      double width;
    
      // ๋‹ค์Œ ํ•„๋“œ๋Š” ๋ชจ์–‘์ด ์›(CIRCLE)์ผ ๋•Œ๋งŒ ์“ฐ์ธ๋‹ค.
      double radius;
    
      // ์›์šฉ ์ƒ์„ฑ์ž
      Figure(double radius) {
          shape = Shape.CIRCLE;
          this.radius = radius;
      }
    
      // ์‚ฌ๊ฐํ˜•์šฉ ์ƒ์„ฑ์ž
      Figure(double length, double width) {
          shape = Shape.RECTANGLE;
          this.length = length;
          this.width = width;
      }
    
      double area() {
          switch(shape) {
              case RECTANGLE:
                  return length * width;
              case CIRCLE:
                  return Math.PI * (radius * radius);
              default:
                  throw new AssertionError(shape);
          }
      }
    }

1๏ธโƒฃ ํƒœ๊ทธ ๋‹ฌ๋ฆฐ ํด๋ž˜์Šค๋Š” ์žฅํ™ฉํ•˜๊ฒŒ, ์˜ค๋ฅ˜๋ฅผ ๋‚ด๊ธฐ ์‰ฝ๊ณ , ๋น„ํšจ์œจ์ ์ด๋‹ค.

2๏ธโƒฃ ํƒœ๊ทธ ๋‹ฌ๋ฆฐ ํด๋ž˜์Šค๋Š” ํด๋ž˜์Šค ๊ณ„์ธต๊ตฌ์กฐ๋ฅผ ์–ด์„คํ”„๊ฒŒ ํ‰๋‚ด๋‚ธ ์•„๋ฅ˜์ผ ๋ฟ์ด๋‹ค.

์ฐธ๊ณ  ์ž๋ฃŒ

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