2014-02-19 258 views
0

我想在abstract class中創建一個abstract static method。我很清楚從this question這是不可能在Java中。什麼是默認的解決方法/思考問題的替代方式/是否可以選擇這樣做看似有效的示例(如下所示)?靜態抽象方法解決方法

動物類和子類:

我有一個基類Animal與各子類。我想強制所有的子類能夠從一個XML字符串創建一個對象。對於這一點,除靜態以外沒有任何意義嗎? E.g:

public void myMainFunction() { 
    ArrayList<Animal> animals = new ArrayList<Animal>(); 
    animals.add(Bird.createFromXML(birdXML)); 
    animals.add(Dog.createFromXML(dogXML)); 
} 

public abstract class Animal { 
    /** 
    * Every animal subclass must be able to be created from XML when required 
    * (E.g. if there is a tag <bird></bird>, bird would call its 'createFromXML' method 
    */ 
    public abstract static Animal createFromXML(String XML); 
} 

public class Bird extends Animal { 
    @Override 
    public static Bird createFromXML(String XML) { 
     // Implementation of how a bird is created with XML 
    } 
} 

public class Dog extends Animal { 
    @Override 
    public static Dog createFromXML(String XML) { 
     // Implementation of how a dog is created with XML 
    } 
} 

所以在我需要一個靜態方法,我需要迫使所有子類有這個靜態方法的實現方式的情況下,是有辦法,我能做到這一點?

+5

查找到抽象工廠和工廠模式。在這裏抽象與Java中關鍵字'abstract'無關。 –

回答

2

您可以創建一個工廠,生產動物對象,下面是給你一個啓動一個樣本:

public void myMainFunction() { 
    ArrayList<Animal> animals = new ArrayList<Animal>(); 
    animals.add(AnimalFactory.createAnimal(Bird.class,birdXML)); 
    animals.add(AnimalFactory.createAnimal(Dog.class,dogXML)); 
} 

public abstract class Animal { 
    /** 
    * Every animal subclass must be able to be created from XML when required 
    * (E.g. if there is a tag <bird></bird>, bird would call its 'createFromXML' method 
    */ 
    public abstract Animal createFromXML(String XML); 
} 

public class Bird extends Animal { 
    @Override 
    public Bird createFromXML(String XML) { 
     // Implementation of how a bird is created with XML 
    } 
} 

public class Dog extends Animal { 
    @Override 
    public Dog createFromXML(String XML) { 
     // Implementation of how a dog is created with XML 
    } 
} 

public class AnimalFactory{ 
    public static <T extends Animal> Animal createAnimal(Class<T> animalClass, String xml) { 
      // Here check class and create instance appropriately and call createFromXml 
      // and return the cat or dog 
    } 
} 
+0

謝謝,這似乎是一個有效的解決方法。儘管你添加的代碼出現錯誤。如果不是'public static Animal createAnimal(Class animalClass,String XML)'? –

+0

是的,也許是因爲我在這裏寫了它只是爲了給你一個想法,而不是運行這個。 :) – Sanjeev

+0

現在更新:) – Sanjeev