2010-07-16 4 views
3

, 자바 (NO 추상적 정적 메서드)에서 작동하지 않습니다 다음 ... Java의 static 팩토리 메서드 [getInstance()]? 물론

public abstract class Animal { 
    public abstract static Animal getInstance(byte[] b); 
} 

public class Dog extends Animal { 
    @Override 
    public static Dog getInstance(byte[] b) { 
     // Woof. 
     return new Dog(...); 
    } 
} 

public class Cat extends Animal { 
    @Override 
    public static Cat getInstance(byte[] b) { 
     // Meow. 
     return new Cat(...); 
    } 
} 

Animal 클래스 자체를 인스턴스화 정적 getInstance 방법을 가지고 요구하는 올바른 방법은 무엇입니까

? 이 메소드는 정적이어야합니다. "보통의"추상적 인 방법은 여기서 이해가되지 않는다.

+0

관련 : http://stackoverflow.com/questions/129267/why-no-static-methods-in-interfaces-

하나의 대안은 Animal 클래스와 별도 AnimalFactory 인터페이스를 정의하는 것입니다 static-fields-and-inner-class-ok 및 http://stackoverflow.com/questions/708336/beginner-factory-pattern-in-java – finnw

답변

6

구현 클래스에 특정 정적 메서드가 있어야한다는 추상 클래스 (또는 인터페이스)를 지정할 방법이 없습니다.

리플렉션을 사용하여 유사한 효과를 얻을 수 있습니다.

public interface AnimalFactory { 
    Animal getInstance(byte[] b); 
} 

public class DogFactory implements AnimalFactory { 
    public Dog getInstance(byte[] b) { 
     return new Dog(...); 
    } 
} 

public interface Animal { 
    // ... 
} 

class Dog implements Animal { 
    // ... 
} 
+1

새로운 인스턴스를 요청하는 것은 전혀 의미가 없습니다. 기존 인스턴스에서. 인스턴스가 아직없는 경우 하나를 얻을 수 없기 때문에. 이것은 클래식 정적 팩토리 메소드가 제공되는 곳입니다 (정적 인 인터페이스 나 추상 메소드를 제공 할 수 없기 때문에 좋은 디자인을 얻기가 어렵습니다). – gyorgyabraham

관련 문제