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檢查?
+1 Darron的回答。另外,一個風格問題:AbstractFactory不是抽象的,所以名稱是誤導性的。 – 2010-11-08 19:31:02