Skip to content

이펙티브 자바 item1: 정적 팩터리 메서드의 5번째 장점이 이해가지 않습니다. #61

@KimChanJin97

Description

@KimChanJin97

[이펙티브 자바 item1: 생성자 대신 정적 팩터리 메서드를 고려하라]

“정적 팩터리 메서드의 5번째 장점: 정적 팩터리 메서드를 작성하는 시점에는 반환할 객체의 클래스가 존재하지 않아도 된다.” 가 와닿지 않습니다. 예제 코드를 찾아봐도 이해가 되질 않는데 이 장점에 대해 토론해보면 좋을 것 같습니다. 참고한 블로그 주소는 다음과 같습니다. [https://jaeseongdev.github.io/development/2021/01/05/이펙티브_자바_아이템_1/](https://jaeseongdev.github.io/development/2021/01/05/%EC%9D%B4%ED%8E%99%ED%8B%B0%EB%B8%8C_%EC%9E%90%EB%B0%94_%EC%95%84%EC%9D%B4%ED%85%9C_1/)

public class Level {
    // 정적 팩토리 메소드
    public static Level of(int score){ // 메서드 바꾸지 않고
        if (score < 50){
            return new Basic(); // 구현체만 바꾸면 된다. (OCP 위반?)
        } else if (score < 80){
            return new Intermediate();
        } else {
            return new Advanced();
        }
    }

    // 어리석은 코드
    Level basic = new Basic();
    Level intermediate = new Intermediate();
    Level advanced = new Advanced();
}
public class Basic extends Level {
}
public class Intermediate extends Level {
}
public class Advanced extends Level {
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions