Open byunghyunkim0 opened 6 months ago
두 가지 이상의 의미를 표현할 수 있으며, 그중 현재 표현하는 의미를 태그 값으로 알려주는 클래스가 있다.
public class FigureWithTag { enum Shape {RECTANGLE, CIRCLE}; // 태그 필드 - 현재 모양을 나타낸다. final Shape shape; // 다음 필드들은 모양이 사각형(RECTANGLE)일 때만 쓰인다. double length; double width; // 다음 필드는 모양이 원(CIRCLE)일 때만 쓰인다. double radius; // 원용 생성자 public FigureWithTag(double radius) { shape = Shape.CIRCLE; this.radius = radius; } // 사각형용 생성자 public FigureWithTag(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); } } }
FigureWithTag figure = new FigureWithTag(0.3, 0.5);
abstract class Figure { abstract double area(); }
// 클래스 계층구조로 변환 abstract class Figure { abstract double area(); }
class Circle extends Figure { final double radius;
Circle(double radius) { this.radius = radius; } @Override double area() { return Math.PI * (radius * radius); }
}
class Rectangle extends Figure { final double length; final double width;
Rectangle(double length, double width) { this.length = length; this.width = width; } @Override double area() { return length * width; }
### 정사각형도 지원하도록 수정하려면? ```java class Square extends Rectangle { Square(double side) { super(side, side); } }
아주 간단하게 수정할수있다!
태그 달린 클래스를 써야 하는 경우는 거의 없다.
Chapter : 4. 클래스와 인터페이스
Item : 23. 태그 달린 클래스보다는 클래스 계층구조를 활용하라
Assignee : byunghyunkim0
🍑 서론
두 가지 이상의 의미를 표현할 수 있으며, 그중 현재 표현하는 의미를 태그 값으로 알려주는 클래스가 있다.
🍑 본론
태그 달린 클래스의 단점
FigureWithTag figure = new FigureWithTag(0.3, 0.5);
태그 달린 클래스를 클래스 계층구조로 변경
class Circle extends Figure { final double radius;
}
class Rectangle extends Figure { final double length; final double width;
}
아주 간단하게 수정할수있다!
🍑 결론
태그 달린 클래스를 써야 하는 경우는 거의 없다.
Referenced by