0

What's the best place for a factory interface to create an instance of another interface?

OptionA: a separate class

public interface InterAFactory {
    InterA createInterA();
}

public interface InterA {
    void doStuff();
}

OptionB: a subclass

public interface InterA {
    public interface Factory {
        InterA createInterA();
    }

    void doStuff();
}

I notice that guava has tended to use B for the immutable collections, but that's for builders, which are slightly different to factories. I also tend towards optionB, as it reduces the number of top-level classes in the package, and it strongly associates the factory with the thing it creates. However, implementations will not be bound or affected by this, and it will make implementations of the factory slightly more verbose. Thoughts?

2 Answers 2

1

Guava builders are kind of different. ImmutableList.Builder only exists because ImmutableList doesn't want to open up its constructor. So the only way to create an ImmutableList is via the Builder, which is a very-closely associated inner class, which makes sense.

In your case, I think it depends on the nature of the objects we're talking about. Consider

interface Vehicle { interface Factory { createVehicle(); }}

class Bmw implements Vehicle {
  // complex code
}

class BmwFactory implements Vehicle.Factory {
  // more complex code
}

class Fiat implements Vehicle {
  public Fiat() { }
  // no need for a factory at all here, but there's still a guilty feeling
  // that inner interface had better been implemented...
}

Which I guess is fine... You just ended up using Vehicle. as pretty much a package name. Personally, I'd go with option a)

0

My personal taste is to use a variation of (a) with generics:

OptionA*: a separate class with generics

public interface Factory<T> {
    T create();
}

So you have only one factory interface for many different types. This is not possible with (b).

I use this in c#/dotnet for a repository factory for different item-types. In java it should be similar.

1
  • The code examples are a generalisation - type-specific arguments will be passed into the factory method & constructor in my specific situation.
    – thecoop
    Dec 2, 2013 at 18:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.