item2 ~ item3
코드 넘나 깔끔...
public class Calzone extends Pizza {
private final boolean sauceInside;
public static class Builder extends Pizza.Builder<Builder> {
private boolean sauseInside = false;
public Builder sauceInde() {
sauseInside = true;
return this;
}
@Override
public Calzone build() {
return new Calzone(this);
}
@Override
protected Builder self() {
return this;
}
}
private Calzone(Builder builder) {
super(builder);
sauceInside = builder.sauseInside;
}
}
빌더는 가변 인자 (vargars) 매개변수를 여러개 사용할 수 있다는 소소한 장점도 있다.
유연한 장점이 있어 언젠가 변수가 늘어날 가능성이 있을 때 써도 좋다고 한다
싱글톤 생성시에는
private 생성자 또는 enum 타입을 사용해서 싱글톤으로 만들 것
public class Elvis {
public static final Elvis INSTANCE = new Elvis();
private Elvis() {
}
}
public class Elvis {
private static final Elvis INSTANCE = new Elvis();
private Elvis() {
}
public static Elvis getInstance() {
return INSTANCE;
}
}
직렬화 (Serialization)
모든 인스턴스 필드에 transient를 추가 (직렬화 하지 않겠다는 뜻) 하고 readResolve 메소드를 다음과 같이 구현하면 된다. (객체 직렬화 API의 비밀 참고)
private Object readResolve() {
return INSTANCE;
}
Enum사용
직렬화/역직렬화 및 리플렉션 호출 문제도 고민할 필요 없는 방법
public enum Elvis {
INSTANCE;
}
코드는 좀 불편하게 느껴지지만 싱글톤을 구현하는 최선의 방법이다. 하지만 이 방법은 Enum 말고 다른 상위 클래스를 상속해야 한다면 사용할 수 없다. (하지만 인터페이스는 구현할 수 있다.)
https://www.oracle.com/technical-resources/articles/java/serializationapi.html
Discover the secrets of the Java Serialization API
We all know the Java platform allows us to create reusable objects in memory. However, all of those objects exist only as long as the Java virtual machine1 remains running. It would be nice if the objects we create could exist beyond the lifetime of the vi
www.oracle.com
'Web > JAVA' 카테고리의 다른 글
[effective java] 3판 요약 보면서 (2) (0) | 2023.04.18 |
---|---|
[Functional Interface] (0) | 2023.04.18 |
[자료구조] DFS, BFS (0) | 2023.04.17 |
[Java] Super (0) | 2023.03.23 |
[Java] Interface Supplier<T> (0) | 2023.03.22 |