Factory Creation Methods Always Static?

Viewed 15680

It's common place for factory classes to be static, and factory methods to be static also.

Did the GOF in the Design Patterns book ever stipulate that factories and their methods MUST be static in order to meet the strict definition of the pattern?

Is having factories+/methods static just a consequence of the pattern? state data is not normally maintained by the factory class, so they're normally static.

6 Answers

It depends on your needs. I generally prefer a static method for creation:

SpaceShip spaceShip = SpaceShipFactory.create();

Also, Java uses static methods for Factories in most cases.

Calendar calendar = Calendar.getInstance();

But if we're gonna create multiple instances from the same factory. Maybe we can prefer non-static way for it. We need some stateful fields as the Algorithm for this purpose.

SSHKeyFactory factory = new SshKeyFactory(Algorithm.RSA);
Key client1Key = factory.createKey();
Key client2Key = factory.createKey();
...

Usage of Static Method is not related to any design pattern. It is the choice of either we use a Class level or an instance level method. Factory class does not requires to maintain any state. So that normally we go for Static method . If it really requires a state, then we create an object to the class and set state to the object. This time we might choose either static or instance method.

Related