티스토리 뷰

기존 코드 

if(구글로그인){
    // 로그인 처리
}else if(인스타로그인){
    // 로그인 처리
}else if(페이스북로그인){
    // 로그인 처리
}else{
    // 로그인 처리
}

문제점 

  1. 새로운 추가가 발생할 때 마다 소스를 추가/변경해 주어야 한다.
  2. 코드의 양이 커진다. 
  3. 복잡도 증가한다. 
  4. 가독성이 떨어진다. 
  5. 부분 테스트 불가능하다. 

리팩토링

인터페이스를 생성하고 각각의 로그인 형태에 따라 클래스로 분리한다.
flyweight pattern과 유사한 형태로 만든다. 각각의 클래스를 자료 구조에 담아 두고 꺼내 이용한다. 

 

설계상에는 Factory를 별도로 만들지 않았습니다. 

Contorller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@RestController
@Slf4j
public class UserAuthRestController {
 
    private Map<String, AuthService> authServiceMap;
 
    @Autowired
    private void setAuthService(List<AuthService> authServices) {
        authServiceMap = new HashMap<>();
        for (AuthService auth : authServices) {
            authServiceMap.put(auth.getAuthType(), auth);
        }
    }
 
    private AuthService getAuthService(String authType) {
        if (authServiceMap.containsKey(authType)) {
            return authServiceMap.get(authType);
        }
        throw new EbloNotFoundException("존재하지 않는 유형입니다.");
    }
 
    @GetMapping("/api/user-auth")
    public User userAuth(User user) {
        AuthService authService = getAuthService(user.getAuthType());
        User rUser = authService.getUserInfo(user);
        // TODO 로그인 관련 처리 후 결과값 반환
 
        return rUser;
    }
}
cs





Interface

1
2
3
4
5
6
7
8
public interface AuthService {
 
    public String getAuthType() ;
    
    public User getUserInfo(User user); 
    
}
 
cs

Service

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Service
public class GoogleAuthService implements AuthService {
 
    private String authType = "google"
    
    @Override
    public String getAuthType() {
    return this.authType;
    }
 
    @Override
    public User getUserInfo(User user) {
    // TODO 1. get userInfo from facebook
    return user;
    }
 
}
cs


새로운 서비스를 추가하는 경우 AuthService 인터페이스를 구현해서 추가하면 자동 적용이 됩니다. 

특정 서비스를 수정하는 경우 해당 서비스만 수정하면 됩니다. 


로그인 프로세스를 예로 들었지만 이런 유사 형태를 자주 경험할 수 있습니다. 

초급 개발자는 더 복잡해졌다고 생각할 수 있겠으나 익숙해지면 쉽게 구현 가능한 형태입니다. 

 

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함