Factory Method Pattern - Limitations

Limitations

There are three limitations associated with the use of the factory method. The first relates to refactoring existing code; the other two relate to extending a class.

  • The first limitation is that refactoring an existing class to use factories breaks existing clients. For example, if class Complex were a standard class, it might have numerous clients with code like:
Complex c = new Complex(-1, 0);
Once we realize that two different factories are needed, we change the class (to the code shown earlier). But since the constructor is now private, the existing client code no longer compiles.
  • The second limitation is that, since the pattern relies on using a private constructor, the class cannot be extended. Any subclass must invoke the inherited constructor, but this cannot be done if that constructor is private.
  • The third limitation is that, if we do extend the class (e.g., by making the constructor protected—this is risky but feasible), the subclass must provide its own re-implementation of all factory methods with exactly the same signatures. For example, if class StrangeComplex extends Complex, then unless StrangeComplex provides its own version of all factory methods, the call StrangeComplex.fromPolar(1, pi); will yield an instance of Complex (the superclass) rather than the expected instance of the subclass. The reflection features of some languages can obviate this issue.

All three problems could be alleviated by altering the underlying programming language to make factories first-class class members (see also Virtual class).

Read more about this topic:  Factory Method Pattern

Famous quotes containing the word limitations:

    ... art transcends its limitations only by staying within them.
    Flannery O’Connor (1925–1964)

    Growing up means letting go of the dearest megalomaniacal dreams of our childhood. Growing up means knowing they can’t be fulfilled. Growing up means gaining the wisdom and skills to get what we want within the limitations imposed by reality—a reality which consists of diminished powers, restricted freedoms and, with the people we love, imperfect connections.
    Judith Viorst (20th century)

    The only rules comedy can tolerate are those of taste, and the only limitations those of libel.
    James Thurber (1894–1961)