2010-06-29 3 views
3

은 가정하자 내가 가진 :instanceof를 사용하는 것보다 형식을 조건부로 생성하는 더 좋고/더 좋은 방법이 있습니까? [자바]

public class FightingZone<MobileSuitso, Background> { 

    private MobileSuitCollection<MobileSuitso> msCollection; 
    private BackgroundInfo<Background> bgInfo; 

    public FightingZone(MobileSuitCollection<MobileSuitso> newCollection, BackgroundInfo<Background> newInfo) { 
     this.msCollection = newCollection; 
     this.bgInfo = newInfo; 
    } 

    ... 

     ...// inside a method 
     MobileSuitCollection temporaryCollection = new MobileSuitCollection<MobileSuitso>(); // /!\ 

} 

문제는 MobileSuitCollection는 인터페이스입니다, 그래서 그것을 인스턴스화 할 수 없습니다. 예를 들어, 내가 할 수있는 :

MobileSuitCollection temporaryCollection = new GundamMeisterCollection<MobileSuitso>(); 
MobileSuitCollection temporaryCollection = new InnovatorCollection<MobileSuitso>(); 
MobileSuitCollection temporaryCollection = new CannonFolderCollection<MobileSuitso>(); 

등은 그러나, temporaryCollection을 조작, 나는 내 클래스에 매개 변수를 통해 전달 된 것과 같은 종류 여야합니다. 그래서이 일을 생각했습니다 :

if (msCollection instanceof GundamMeisterCollection) { 
    ... 
} else if (msCollection instanceof InnovatorCollection) { 
    ... 
} ... 

나는 그것이 끔찍한 것을 알고 있습니다. 이 작업을 수행하는 더 좋은 방법이 있습니까? 초기 유형에서 사용하는 클래스에 대한 참조를 유지 한 다음 temporaryCollection을 인스턴스화 할 수 있습니까?

당신이 만약 절에 배치 코드는 Visitor에 배치 될 수

답변

2

:

// Generics skipped for brevity 
interface MobileSuitCollectionVisitor { 
    handleCollection(GundamMeisterCollection collection); 
    handleCollection(InnovatorCollection collection); 
    handleCollection(CannonFolderCollection collection) 
} 

class ConcreteVisitor implements MobileSuitCollectionVisitor { 
    // place all of the logic in the implemented methods 
} 

다음 MobileSuitCollection을 할 수는 방법이 있습니다

void visit(MobileSuitCollectionVisitor visitor); 

그리고 MobileSuitCollection의 각 구현을 간단하게 가지고있다

public void visit(MobileSuitCollectionVisitor visitor) { 
    visitor.handleCollection(this); 
} 
+0

Reflection을 사용하여 클래스 이름을 가져 와서 거기에서 인스턴스를 생성하려고합니다. 가능하다면 코드를 깨끗하게 만들지 않겠습니까? 아니면 아직도이 방법이 선호됩니까? –

+0

Reflection을 사용하려면 class name 대신 class object를 사용하십시오. 마찬가지로 :' cl = collection.getClass(); Interface inst = cl.newInstance();' –

+0

반사가 최후의 수단이어야합니다. 위의 접근 방식은 객체 지향적 인 접근 방식입니다. – Bozho

0

신속하고 더러운 방법 원래 컬렉션을 복제 한 다음 필요에 따라 조작하는 것입니다. 더 좋은 방법은 인터페이스에 newInstance() 메소드를 추가하거나 FightingZone으로 팩토리를 전달하는 것입니다.

관련 문제