2010-11-08 59 views
0

的java我目前使用我廠這樣的工廠模式問題

public class AbstractFactory 
{ 
    public static AbstractHeader parseHeader(File file) 
    { 
      if(AFactory.canRead(file))return AFactory.parseHeader(file); 
      if(BFactory.canRead(file))return BFactory.parseHeader(file); 

      throw new UnsupportedOperationException("File ["+file+"] not supported"); 
    } 

    public static AbstractContent parseContent(AbstractHeader h) 
    { 
      if(h instanceof AHeader){ 
        return AFactory.parseContent((AHeader) h); 
      } 
      if(h instanceof BHeader){ 
        return BFactory.parseContent((BHeader) h); 
      } 
      throw new UnsupportedOperationException("Header not supported"); 
    } 
} 

的parseHeader()將返回一個實例要麼AHeader或BHeader,並在以後的時間會要求AbstractContent。有一個更好的方法嗎 ?帶着instanceof檢查?

+0

+1 Darron的回答。另外,一個風格問題:AbstractFactory不是抽象的,所以名稱是誤導性的。 – 2010-11-08 19:31:02

回答

5

下面的代碼添加到您現有的類:

public abstract class AbstractHeader { 
    abstract AbstractContent parseContent(); 
} 

public class AHeader extends AbstractHeader { 
    public AbstractContent parseContent() { 
     return AFactory.parseContent((AHeader) h); 
    } 
} 

public class BHeader extends AbstractHeader { 
    public AbstractContent parseContent() { 
     return BFactory.parseContent((AHeader) h); 
    } 
} 

現在你可以叫h.parseContent()。這被稱爲多態性。

+0

+1非常乾淨的解決方案。使課堂更加容易。 – helpermethod 2010-11-08 18:42:48

+0

off-course!我對工廠的想法很盲目,甚至沒有想到更簡單的解決方案! – Anon 2010-11-08 18:54:12