2012-07-31 2 views
1

엔티티라는 루트 클래스가 있습니다. 또한 Entity의 하위 유형에 대해 CRUD 작업을 수행하는 서비스 클래스가 있습니다. 그래서, 내 서비스 클래스 정의가키와 값에 관련된 계층 구조가 적용되는 맵을 정의하는 방법은 무엇입니까?

class Entity { 
    //the root class 
} 

class Service<T extends Entity> { 
    //root service class containing common CRUD operations 
} 


class SomeEntity extends Entity { 
} 

class SomeService extends Service<SomeEntity> { 
} 

내가 유지하는이 패턴에게지도 엔터티의 클래스에 따라 - 위는 적용하지 않습니다, 그러나

Map<Class<? extends Entity>, Service<? extends Entity>> = serviceMap 
new HashMap<Class<? extends Entity>, Service<? extends Entity>>(); 

처럼> 해당 서비스에를 그 클래스와 해당 서비스는 동일한 계층 구조에 속합니다. 따라서 캐스팅 후에도 클라이언트 코드를 다시 캐스팅해야합니다. 다음을 피하는 방법? 그리고 열쇠와 가치 사이에 엄격한 관계를 강요합니까?

public <T extends Entity> Service<T> get(Class<T> clazz) { 
    return (Service<T>) serviceMap.get(clazz); 
    } 

    //example of client code 
    SomeService service = (SomeService) serviceRegistry.get(SomeEntity.class); 
+0

엔티티와 서비스간에 항상 1 : 1 매핑이 있습니까? 또는 특정 시점에 하나의 서비스를 사용하지만 나중에 다른 서비스를 사용할 필요가 있습니까? 즉, 언제지도를 업데이트해야합니까? –

+0

http://stackoverflow.com/questions/11720065/how-to-work-with-a-generic-map-whose-key-and-values-belong-to-a-ident-hierarchy의 가능한 (거의) 복제본 ? rq = 1 –

답변

0

불행히도, 당신이하고 싶은 일을 할 수 없습니다. 그것은 불가능합니다!

그러나 실제로는 Service 구현이 무엇인지 알 필요가 없습니다. Service은 호출 할 클라이언트 코드에 필요한 모든 메소드를 제공해야합니다. 안녕 다형성! 실제 구현에 대해 너무 많은 신경 안

Service<? extends Entity> getService(Class<?> entityClass) { 
    return serviceMap.get(entityClass); 
} 

클라이언트 코드 : 개인적으로, 난 그냥에 약간 get 메소드를 변경할 것 당신이 알고있는 경우

Service<? extends Entity> service = getService(SomeEntity.class); 
service.save(myEntity); 

또 다른 옵션이 무엇인지 엔티티 유형

<T extends Service<? extends Entity>> T getService(Class<?> entityClass, Class<T> serviceClass) { 
    return serviceClass.cast(serviceMap.get(entityClass)); 
} 

인정 하듯이, 위의 방법 중 어느 것도 보장 : 당신이 서비스는 다음 예를 들어, Service 클래스에 전달하고 캐스팅을 위해 그것을 사용할 수 있습니다 할 때입니다 SomeEntity.classMap의 SomeService 인스턴스와 쌍을 이룹니다.

관련 문제