JAVA
26.Java Lombok/빌드업패턴/Optional
네스이
2022. 9. 19. 17:14
2022.09.15/19.목/월
1.Lombok/빌드업패턴
-Book class
package dev.syntax;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@NoArgsConstructor //기본 생성자 메서드 자동 완성 어노테이션
@AllArgsConstructor //모든 필드를 매개변수로 받는 생성자
@Setter @Getter
@ToString
@Builder
public class Book {
private String name;
private String author;
private String publisher;
// //점층적 생성자 패턴
// public Book(String name) {
// this.name = name;
// }
// public Book(String name, String author) {
// this.name = name;
// this.author = author;
// }
// public Book(String name, String author, String publisher) {
// super();
// this.name = name;
// this.author = author;
// this.publisher = publisher;
// }
}
package dev.syntax;
public class BookTest {
public static void main(String[] args) {
// Book b1 = new Book();
//
// b1.setName("노인과 바다");
// b1.setAuthor("헤밍웨이");
//
// System.out.println(b1);
Book b2 = new Book("알베르 카뮈", "시지프 신화", "민음사");
// Book b3 = new Book("어린왕자", "생텍쥐페리");
Book b4 = new Book.BookBuilder().name("어린왕자").build();
}
}
-Car class
package dev.syntax;
import lombok.ToString;
@ToString
public class Car {
private String type; //SUV, 중형, 세단 등
private String brand; //자동차 브랜드
private String name;
private int price;
private Car(Builder builder) {
this.type = builder.type;
this.brand = builder.brand;
this.name = builder.name;
this.price = builder.price;
}
//빌드업 패턴
//inner 클래스 : Car 클래스 내부에서만 사용하는 클래스
public static class Builder {
private String type;
private String brand;
private String name;
private int price;
//일반 메서드(필드의 값을 세팅해주는 메서드)
public Builder type(String type) {
this.type = type;
return this;
}
public Builder brand(String brand) {
this.brand = brand;
return this;
}
public Builder name(String name) {
this.name = name;
return this;
}
public Builder price(int price) {
this.price = price;
return this;
}
//실제 인스턴스(Car) 생성 처리 메서드
public Car build() {
return new Car(this);
}
}
}
package dev.syntax;
public class carTest {
public static void main(String[] args) {
Car mustang = new Car.Builder().name("머스탱").brand("포드").build();
System.out.println(mustang);
}
}
2.Optional
package dev.syntax;
import java.util.Optional;
import javax.management.RuntimeErrorException;
public class App {
public static void main(String[] args) {
//Optional의 생성
//1.of() : null이 아닌 값을 가지고 Optional을 생성할 때 사용하는 메서드
Optional<String> opWithValue = Optional.of("어떤 문자열 값"); //"어떤 문자열 값"을 값으로 가지고 있는 Optional 객체 생성
System.out.println(opWithValue);
//2.ofNullable() : null일 수도 있는 어떤 값을 가지고 Optional 객체를 생성할 때 사용하는 메서드
//-> 인수로 전달한 값이 null이어도 NPE(Null Pointer Exception)가 발생하지 않음
//값이 없는(할당되지 않은) Optional 객체를 생성하게 됨
Optional<String> opWithNullValue = Optional.ofNullable(null);
System.out.println(opWithNullValue); //값이 없어도 NPE가 발생하지 않음
//get() : Optional로 감싸져있는 값 취득하는 메서드
String str = opWithValue.get();
System.out.println(str);
//3.empty() : 값이 없는 Optional 객체 그 자체를 생성할 때 사용하는 메서드
Optional<String> opWithEmptyValue = Optional.empty();
System.out.println(opWithEmptyValue);
// opWithEmptyValue.get(); //값이 비어있는 Optional에 get()을 호출할 경우, NPE 발생ㅉ
//Optional 내에 값이 있는지 없는지 확인 isPresent(), isEmpty(java 11부터 가능)
System.out.println(opWithValue.isPresent()); //값이 있기 때문에 true 반환
System.out.println(opWithValue.isEmpty()); //false
//값이 있을 경우에 취할 동작(if - els) - ifPresent(), ifPresntOrElse()
opWithValue.ifPresent(value -> doSome(value)); //if(value != null) doSome(value);와 같은 코드
opWithEmptyValue.ifPresentOrElse(value -> doSome(value), () -> doOther());
//Optional 내에 값이 없을 때 다른 값으로 대체하여 사용하려고 할 때
String result = opWithValue.orElse("기본 값");
System.out.println("result : " + result);
String result1 = opWithEmptyValue.orElse("기본 값");
System.out.println("result1 : " + result1);
//orElseThrow(), 값이 없을 경우 예외 발생시킴, 있을 경우 해당 값 반환(get())
String result3 = opWithValue.orElseThrow();
System.out.println("result3 : " + result3);
// String result4 = opWithEmptyValue.orElseThrow();
// System.out.println(result4);
String result5 = opWithEmptyValue.orElseThrow(() -> new RuntimeException("그런 값 없는데요?"));
}
public static void doSome(String value) {
System.out.println(value + "를 한다.");
}
public static void doOther() {
System.out.println("다른 것을 한다.");
}
}