JAVA | 객체 생성자를 함수 인터페이스로 다루기

주싱·2022년 3월 21일
0

Java

목록 보기
2/6

JAVA 에서 생성자를 함수 인터페이스로 다루는 방법을 찾아보았다.
참조 사이트

01. Function<T, R> 활용하기

Function<String, Student> constructor = Student::new; 
Student one = constructor.apply("Han");

class Student {
   private String name;
   public Student(String name) {
      this.name = name;
}

02. @FunctinalInterface 활용하기

@FunctinalInterface 어노테이션을 활용하면 내가 원하는 생성자 인터페이스를 더 유연하게 정의하고 활용할 수 있는 것 같다.

@FunctionalInterface
interface MyFunctionalInterface {
   Student getStudent(String name);
}

...

MyFunctionalInterface constructor = Student::new;
Student one = constructor.getStudent("Han"); 

03. 내 프로젝트에 적용하기

수신한 메시지의 ID 를 키값으로 메시지 객체 생성자를 Map 에서 관리하여 사용할 수 있도록 구현해 보았다.

@FunctionalInterface
interface MessageConstructor {
    Message construct(String[] line);
}
private final Map<String, MessageConstructor> idToConstructorMap = new HashMap<>();
...
idToConstructorMap.put(MessageSpec.SET_TARGET_ALL.id(), TargetResponse::new);
profile
소프트웨어 엔지니어, 일상

0개의 댓글