0

I am trying to understand the factory design pattern and how it can be implemented in Javascript. So far what I understood is factory design pattern helps to create an instance of more specific class that inherits from a general abstract class.

So I was reading this article. I stumbled upon second point of drawbacks of constructors and class which states:

Details of instantiation get leaked into the calling API (via the 'new' [keyword] requirement):
All callers are tightly coupled to the constructor implementation. If you ever need the additional flexibility of the factory, the refactor is a breaking change. Class to factory refactors are common enough that they appear in the seminal Refactoring book, “Refactoring: Improving the Design of Existing Code” by Martin Fowler, Kent Beck, John Brant, William Opdyke, and Don Roberts.

What does details of instantiation get leaked into the calling API mean?

Erik Eidt
  • 34,819
Pravin
  • 111

1 Answers1

1

Details of instantiation get leaked if you don't use a factory.

Suppose you have an abstract Shape class, which has a Circle and a Polygon subclass, the latter having a Triangle and Square subclass.

If you want to instantiate somewhere in your code some Shape objects, your code will have to know not only about Shape, but also about every concrete subclass it might have to instantiate, as well as the parameters to use to invoke the corresponding constructor.

Your specific instantiation code will hence depend on a lot of details (that leaked). Example:

 int shapetype=random();  
 if (shapetype==0) 
      myshape = new Circle(random(), random()); 
 else if (shapetype==2)
      myshape = new Square(random());  
 ...
 myshape.draw();  

If on the other hand you'd use a factory, the using class would only have to know about the abstract Shape class and how to invoke the factory. It doesn't have to know anything about the subclasses and constructor parameters, thus making your code less dependent on other classes.

  myshape = shapefactory (random());
  myshape.draw(); 
Christophe
  • 81,699