Is factory design pattern can only be used when there is a polymorphic behavior exists?
-
1We usually just call non-polymorphic factories "constructors". – Miles Budnek Aug 04 '22 at 18:15
-
1Obviously not. You can use a factory whenever you want. There is nothing that _forces_ you to use or not use a design pattern. – David L Aug 04 '22 at 18:15
-
1afaik the go4 pattern is specifically about creating objects of different type. Sometimes I need to pass around a function that creates objects (of one type) because I cannot pass around a constructor, I call the function object a "factory" and I don't think this will create lots of confusion among ppl familiar with the factory pattern – 463035818_is_not_an_ai Aug 04 '22 at 19:06
2 Answers
One use of the factory pattern occurs because there is no such thing as a virtual constructor. If you want to create an object where its specific class depends on runtime polymorphic behavior, you can let the factory's create
member function be a virtual function.
However, this is not the only use case for a factory class. Off the top of my head another use for factory would be to enforce two-stage initialization. If all the objects your factory creates require an initialize
member function to be called on them and you can't do it in the constructor for whatever reason (say, for example, you want to use shared_from_this
; it won't be valid in the constructor). The create member function in the factory can call initialize
before returning the object.

- 8,592
- 1
- 29
- 46
You use the factory pattern if you want to be able to change the concrete type that is created later on - in other words to use polymorphism to return an instance of a derived class in the form of the base class.
So polymorphism is a precondition for the factory pattern to work. Without polymorphism, you couldn't return an instance of a derived class in the form of the base class.

- 20,838
- 4
- 31
- 55