DEV Community

Discussion on: Explain Factory Pattern Like I'm Five

nestedsoftware profile image
Nested Software • Edited on

If you just need to create an instance of a single class, then something like new Class() is totally fine. Let's say though you find yourself writing the same conditional code, like below, in multiple places:

let c = null;
if (condition1) {
  c = new Class1();
} else if (condition2) {
  c = new Class2();
} else {
  c = new Class3();


You don't want to duplicate this logic, so a factory will allow you to put this conditional logic to instantiate the object you want in one place. For example:

const c = createClassInstance(config);

// createClassInstance is a factory function. 
// 'config' is some kind of object that 
// contains enough information for the factory 
// to decide what kind of object you want the 
// factory to make for you.
function createClassInstance(config) {
  if (condition1(config)) {
    return new Class1();

  if (condition2(config)) {
    return new Class2();

  return new Class3();

We assume that Class1, Class2, and Class3 all have the function use.

With languages that support "duck typing", as long as the classes all support the use method, that's good enough for this to work. In some cases these classes may all be subclasses of a common base class or implement a common interface. With statically typed languages, I think that has to be the case - it is in fact the case with a language like Java for example.

There are some other cases where you may want to use something like a factory. For example, the Singleton pattern is used to make sure you always get the same instance of an object each time you ask for one anywhere in the code. You can use a factory function to do this. The function will make sure that you're always getting the same instance. Oftentimes this is written to operate lazily, so you'd check to see if you had an instance already, and if so, you'd return that instance. Otherwise you'd create one first, then return it. If you have some sort of connection pool, the same kind of idea can be applied. So I think there are many situations in which you might want to use something along the lines of a factory.