2
votes

Title pretty much sums it up.

I have a factory class that will construct an instance of another class when it's create() method is called. I have setup my Factory Class to be a singleton, which forces invokation to look as such:

SomeClass clazz = (SomeClass) FactoryClass.getInstance().create(ENUM.TYPE);

This guarantees that my Factory is thread safe, but may cause blocking, etc.

If my factory was not a singleton, I could instead set my .create() method be static, which would achieve similar results.

SomeClass clazz = (SomeClass) FactoryClass.create(ENUM.TYPE);

Assuming multiple threads may attempt to create instances of objects via the FactoryClass, which is better? Don't both ways of doing this provide the same level of thread safety?

1
The thread safety would come from all necessary objects being created locally, ie. in the method body. - Sotirios Delimanolis
The singleton approach allows you to switch between multiple implementations of the factory. - Detheroc
@Detheroc as-in multiple factories? i'm not sure I understand, sorry. - SnakeDoc
In addition to @Detheroc: the singleton approach allows you to pass an (the) instance of the factory to another method. - Vincent van der Weele
@SnakeDoc typo, corrected it :) - Vincent van der Weele

1 Answers

4
votes

Neither has an impact on thread-safety. The threading issues reside in the create method's implementation. A static method could create an instance (or get the singleton) and call an instance method so there is really no difference.

Exposing the Singleton is simply an API choice in how you want it to look and feel.

That said, static methods are more challenging to mock in a testing environment so that might be something to consider.