2017-09-20 2 views
0

클래스 (엔티티)와 방문자 디자인 패턴이 결국 파생 된 추상 클래스라는 점에서 관리자 메소드 (코드의 마지막 스 니펫)에서 대/소문자를 사용하지 않는 방법은 조금 혼란 스럽습니다. 아래에는 BaseEntity라는 엔티티에 대한 추상 클래스가 있습니다. 실제 사례가 아니라 의사 코드입니다.방문자가있는 추상 클래스 - typeOf와 비슷합니다.

public abstract class BaseEntity { 

    @Reference 
    protected List<String> items = new ArrayList<>(); 

    public BaseEntity() { 
    } 

    public List<String> getItems() { 
     return items; 
    } 

    public void setItems(List<String> items) { 
     this.items = items; 
    } 
} 

아래에는 추상 클래스에서 3 개의 파생 클래스가 있습니다.

@Entity("CollectionA") 
public class EntityA extends BaseEntity { 
    //code 
} 

@Entity("CollectionB") 
public class EntityB extends BaseEntity { 
    //code 
} 

@Entity("CollectionC") 
public class EntityC extends BaseEntity { 
    //code 
} 

그런 다음 내 관리자에서 instanceOf를 사용하지 않으려 고 방문자를 재사용했습니다.

public interface UpdateEntityVisitor { 

    void create(EntityA entityA); 

    void create(EntityB entityB); 

    void create(EntityC entityC); 
} 

public class UpdateEntityVisitorImpl implements UpdateEntityVisitor { 

    private final Factory factory; 

    public UpdateEntityVisitorImpl() { 
     factory = new FactoryImpl(); 
    } 

    public UpdateEntityVisitorImpl(Factory factory) { 
     this.factory = factory; 
    } 

    @Override 
    public void create(EntityA entityA) { 
     factory.getEntityA().create(entityA); 
    } 

    @Override 
    public void create(EntityB entityB) { 
     factory.getEntityB().create(entityB); 
    } 

    @Override 
    public void create(EntityC entityC) { 
     factory.getEntityC().create(entityC); 
    } 
} 

는 마지막으로 내가 적절한 클래스에 아래 BaseEntity에서지지 않도록하고 싶은 방법, 아래가 내 매니저 클래스입니다. 매니저에서 방문자 클래스보다 재사용 할 수있는 방법이 있습니까?

public void updateEntity(BaseEntity entity) { 
    if (checkSmth()) { 
     updateCollectionA((EntityA) entity); 
    } else { 
     updateCollectionB((EntityB) entity); 
    } 
} 

나는 대해서 typeof https://github.com/nurkiewicz/typeof이라는 매우 유용한 라이브러리를 찾았지만 내 현재 팀에 좀 더 명확하게하기 위해 다른 방법이 있는지 궁금했다.

답변

0

제네릭 사용은 작동합니까?

public <T extends BaseEntity> void updateEntity(T entity) 
{ 
    if (checkSmth()) 
     updateCollectionA(entity); 
    else 
     updateCollectionB(entity); 
} 
+0

감사합니다. 물론 그걸 시도해 보았습니다. 사실 updateCollectionA와 updateCollectionB는 EntityA와 EntityB와 같은 적절한 클래스를 사용하고 각각의 메소드는 적절한 DAO를 사용하여 작업을 실행합니다. 불행히도 제네릭은 허용되지 않습니다. 추신. 우리는 주된 장애물 인 것처럼 보이는 스프링을 사용하지 않습니다. –