은 가정하자 내가 가진 :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
에 배치 될 수
Reflection을 사용하여 클래스 이름을 가져 와서 거기에서 인스턴스를 생성하려고합니다. 가능하다면 코드를 깨끗하게 만들지 않겠습니까? 아니면 아직도이 방법이 선호됩니까? –
Reflection을 사용하려면 class name 대신 class object를 사용하십시오. 마찬가지로 :' cl = collection.getClass(); Interface inst = cl.newInstance();' –
반사가 최후의 수단이어야합니다. 위의 접근 방식은 객체 지향적 인 접근 방식입니다. – Bozho