0

I'm currently using my factory like this:

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");
    }
}

the parseHeader() will return an instance of either AHeader or BHeader, and in a later time will ask for the AbstractContent. Is there a better way to do this ? Get away with the instanceof checks ?

1
  • +1 to Darron's answer. Also, a matter of style: AbstractFactory is not abstract, so the name is misleading. Commented Nov 8, 2010 at 19:31

1 Answer 1

5

Add the following code to your existing classes:

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);
    }
}

Now you can just call h.parseContent(). This is called polymorphism.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 Nice and clean solution. Makes extending the class very easy.
off-course ! I was so blind with the factory idea that I didn't even thought of the simpler solution !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.