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:
- 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
extendsComplex
, then unlessStrangeComplex
provides its own version of all factory methods, the call StrangeComplex.fromPolar(1, pi); will yield an instance ofComplex
(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 OConnor (19251964)
“No man could bring himself to reveal his true character, and, above all, his true limitations as a citizen and a Christian, his true meannesses, his true imbecilities, to his friends, or even to his wife. Honest autobiography is therefore a contradiction in terms: the moment a man considers himself, even in petto, he tries to gild and fresco himself.”
—H.L. (Henry Lewis)
“To note an artists 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 (18761947)