이펙티브 자바23 - 태그 달린 클래스보다는 클래스 계층구조 활용

참치돌고래·2022년 7월 29일
0
class Figure {
	enum Shap { RECTANGLE, CIRCLE };
    
    final Shape shape;
    
    double length;
    double width;
    double radius;
    
    Figure(double radius) {
    	this.shape = Shape.CIRCLE;
        this.radius = radius
    }
    
    Figure(double length, double width) {
    	this.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 AssertionsError(shape);
    }

태그 달린 클래스의 단점 : 열거 타입 선언, 태그 필드, switch 문 -> 메모리 많이 사용

태그 달린 클래스는 장황하고, 오류를 내기 쉽고, 비효율적이다.

태그 달린 클래스를 클래스 계층 구조로 바꾸는 방법

  1. 태그 값에 따라 동작이 달라지는 메서드들을 루트 클래스의 추상 메서드로 선언
  2. 태그 값에 상관없이 동작이 일정한 메서드들을 루트 클래스에 일반 메서드로 추가.
  3. 모든 하위 클래스에서 공통으로 사용하는 데이터 필드들도 전부 루트 클래스로 올린다.

태그 달린 클래스를 클래스 계층 구조로 변환

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; }
}
profile
안녕하세요

0개의 댓글