반응형
함수형 프로그램을 위해
SAM (Single Abstract Method ) 필요
불변성 유지 필요 ( record 로 구현함 jdk 14 미리보기 에 나옴 )
POJO 를 이용한 불변성 구현
1. 일반
package kr.samdogs.study.func.pojo;
import java.time.LocalDateTime;
import java.util.Objects;
//변경불가능 유지를 위해 final class
public final class User {
private String username;
private boolean active;
private LocalDateTime lastLogin;
public User(String username,
boolean active,
LocalDateTime lastLogin) {
this.username = username;
this.active = active;
this.lastLogin = lastLogin;
}
/* getter setter, hashCode, equals 이클립스 자동생성 */
public void setUsername(String username) {
this.username = username;
}
public void setActive(boolean active) {
this.active = active;
}
public void setLastLogin(LocalDateTime lastLogin) {
this.lastLogin = lastLogin;
}
public String getUsername() {
return username;
}
public boolean isActive() {
return active;
}
public LocalDateTime getLastLogin() {
return lastLogin;
}
@Override
public int hashCode() {
return Objects.hash(active, lastLogin, username);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
return active == other.active && Objects.equals(lastLogin, other.lastLogin)
&& Objects.equals(username, other.username);
}
//자동생성에서 조금 수정함
@Override
public String toString() {
return new StringBuilder().append("User [username=")
.append(username)
.append(", active=")
.append(active)
.append(", lastLogin=")
.append(lastLogin)
.append("]").toString();
}
}
2. 불변 POJO 만들기
package kr.samdogs.study.func.pojo;
import java.time.LocalDateTime;
import java.util.Objects;
//변경불가능 유지를 위해 final class
public final class User {
//변수의 불변을 위해 final 추가
private final String username;
private final boolean active;
private final LocalDateTime lastLogin;
public User(String username,
boolean active,
LocalDateTime lastLogin) {
this.username = username;
this.active = active;
this.lastLogin = lastLogin;
}
/* getter setter, hashCode, equals 이클립스 자동생성 */
// 불변변수이므로 set 함수 삭제
public String getUsername() {
return username;
}
public boolean isActive() {
return active;
}
public LocalDateTime getLastLogin() {
return lastLogin;
}
@Override
public int hashCode() {
return Objects.hash(active, lastLogin, username);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
return active == other.active && Objects.equals(lastLogin, other.lastLogin)
&& Objects.equals(username, other.username);
}
//자동생성에서 조금 수정함
@Override
public String toString() {
return new StringBuilder().append("User [username=")
.append(username)
.append(", active=")
.append(active)
.append(", lastLogin=")
.append(lastLogin)
.append("]").toString();
}
}
3. record 이용해서 만들기 (JDK14 이상부터 가능)
public record User(String username,
boolean active,
LocalDateTime lastLogin) {
//생략
}
반응형