[CowAPI] 23. Factory Pattern

준돌·2022년 7월 6일
0

오늘의 Cow

목록 보기
28/45

1. 문제

  • API로 AI 서비스를 제공해주는 기능을 구현 해야합니다.
  • 기존의 방식의 MVC 패턴만을 사용한다면 구현할 수 있습니다.
  • 하지만, 새로운 모델이 추가될때마다 Controller layer에 함수를 새로 작성해야하는 문제가 있습니다.

2. 원인

  • 계속해서 새로운 모델이 추가 될때마다 최대한 중복을 줄이고 안정적으로 모델을 구현하고자 합니다.

3. 해결방법

  • 팩토리 패턴을 적용하여 Ai 모델을 객체로 객체지향 프로그래밍을 합니다.

4. 코드

// 1. Controller

@RestController
@RequiredArgsConstructor
public class AiApiController {
private final AiFactory aiFactory;

    @PostMapping("/ai/{name}")
    public AiResponse response() {
    	AiModel aiModel = aiFactory.getModel(name);
        return aiModel.response(...);
    }
}
// 2. Factory : Ai 모델을 생성하는 팩토리

@Component
@RequiredArgsConstructor
public class AiFactory {
    private final AiApiService aiApiService;

    public AiModel getModel(String name) {
        if(name.equals("vgg")) {
            return new VggModel(aiApiService);
        }

        else{
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "존재하지 않는 서비스입니다.");
        }
    }

}
// 3. Factory가 생성하는 Ai 모델입니다.
// AiModel을 implements 하여 필요한 메소드를 오버라이딩합니다.

@RequiredArgsConstructor
public class VggModel implements AiModel {
    private final AiApiService aiApiService;

    @Override
    public void isValidUser(UsersDto usersDto) {
        aiApiService.isValidUser(usersDto);
    }

    @Override
    public AiResponse response(...) {
        return aiApiService.vggResponse(...);
    }
}
//4. AiModel : Ai 모델의 인터페이스로 Ai모델을 추상화 합니다. 

public interface AiModel {
    void isValidUser(UsersDto usersDto);
    AiResponse response(...);
}
// 5. Service
// Service layer 이며 각각의 Ai 객체들이 사용할 로직들 입니다.

@Service
@RequiredArgsConstructor
public class AiApiService {
...


    public void isValidUser(UsersDto usersDto) {
        ...
    }
    
    public VggResponseDto vggResponse(...) {
    	...
	}
    
  • 팩토리 패턴을 적용하여 Controller layer에서 하나의 함수로 안정적으로 AI 모델 객체를 생성할 수 있게 되었습니다.
profile
눈 내리는 겨울이 좋아!

0개의 댓글