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)

    To note an artist’s limitations is but to define his talent. A reporter can write equally well about everything that is presented to his view, but a creative writer can do his best only with what lies within the range and character of his deepest sympathies.
    Willa Cather (1876–1947)

    That all may be so, but when I begin to exercise that power I am not conscious of the power, but only of the limitations imposed on me.
    William Howard Taft (1857–1930)