JS: Polymorphism
Theory: Factory (Pattern)
Using subtype polymorphism doesn't remove conditional constructs, except in some dispatching cases, such as by key or filename.
More often, the conditional construct is left alone only. When we select a suitable implementation, we use it within the polymorphic function directly, without conditions.
In the previous lesson, we looked at an example function that selects the desired way of implementing the strategy based on the user's age and returns it:
Here we see a function that selects the desired class, creates the object, and then returns it. Programmers call it a factory method. We can implement a factory in any way, including all the methods we've learned in this course.
Generally, we can call a factory anything that creates an object. It doesn't have to use different classes — there could be only one class. But the creation process involves some preliminary calculations. In real projects, factories can be quite large.
We often implement factories as classes with a static method called factory.
Factories themselves don't make objects because it's not an abstraction of data, and it makes no sense to substitute them. Otherwise, you'll get substitutes for substitutes:
Class dispatch
JavaScript allows you to create objects using a class reference:
This syntax gives you great scope for dispatching. For example, in some cases, it'll be possible to get away from the conditional structures completely:

