Talk:Factory method pattern

message: How is this any better than providing parameterized constructors in a class and having the client call the appropriate one?  It seems
using a class factory presents no clear advantages compared to the normal method of calling the correct parameterized constructor from the client
code.  What advantages do factories have?  —Preceding unsigned comment added by 68.100.251.126 (talk) 16:39, 29 January 2008 (UTC)
replies: text: Try writing the Complex class example in the article, and you will see the advantage. Esben (talk) 18:28, 6 February 2008 (UTC)
thread_title: What's the advantage?

message: The third limitation in the Limitations section has an unsubstantiated comment, "this is risky but possible".  I do not see the risk.
:I too do not see this risk. The entire point of the protected keyword is to allow inherited classes access to methods. --Odie5533 02:07, 5 August 2007 (UTC)
replies: text: The third limitation does not really concern that case. Using the protected keyword will in fact allow inheritance of the constructor, but the subclass must still implement its own methods to call its own inherited constructor. Therefore, perhaps the wording was incorrect, but the idea that it is risky to attempt to use inheritance in that situation holds true and it is important to be explicit about the inheritance limitation of this pattern. 192.5.246.220 (talk) 01:33, 19 March 2008 (UTC)

text: The risk is in the fact that the 'protected' keyword provides visibility to the entire package. As a result, any class in the package may use the constructor to construct an instance, instead of using the factory method. This may lead to inconsistent instances, such as instances having properties that are uninitialized, but that are expected to be initialized, because the factory method initializes them. 82.176.252.66 (talk) 11:15, 31 January 2009 (UTC)
replies: text:  I think this is inaccurate.  The use of no keyword modifier would result in package-private access, which as you state gives visibility of the constructor to the entire package.  However the 'protected' keyword will only give subclasses access to the constructor, so any class in the package would not have access. 93.97.156.254 (talk) 09:12, 16 May 2009 (UTC)
replies: text:  The 'protected' keyword modifier in Java does allow unrelated classes of the same package to access protected fields/methods. Conversely, 'default' access doesn't allow access to subclasses that aren't in the same package. I know it sounds counter-intuitive, but that's how it works in Java. 81.208.34.156 (talk) 10:44, 16 September 2011 (UTC)
thread_title:  The third limitation 

message: All three problems can be alleviated by making factories
 first-class class members rather than using the design pattern.. [1]
The actual citation from the text is as follows:
 Interface (or protocol) can be separated from
 implementation, but in order to select a particular
 implementation of a given protocol one must be familiar
 with at least one of these implementations. Our solution
 to this cyclic dilemma is by making the selection of an
 implementation part of the interface. In the
 object-oriented terminology, this means that we allow a
 class to offer a set of services, what we call factories,
 for generating instances of its various subclasses.
 Factories are first-class class members (alongside
 methods and constructors), but, unlike constructors,
 factories encapsulate instance management decisions
 without affecting the class’s clients.
After reading that, the original statement about solving the problems doesn't make any sense to me and seems incorrect. --Odie5533 02:14, 5 August 2007 (UTC)
thread_title:  Misunderstanding in Citation 

message: The complex number example doesn't seem to be an example of the factory method pattern. In all cases, a Complex class is instantiated. —Ben FrantzDale 07:02, 12 November 2007 (UTC)
replies: text: The problem seems to be that this page is redirected to from factory method. The idiom to use functions that return objects but are not constructors are sometimes called (perhaps mistakenly?) factory methods, and sometimes "named constructors" (which has no page). Not sure what to do in this case, as the idiom is pretty common in the many languages which requires the constructor to have a specific name (C++, Java are two obvious examples). Personally, I'd argue that limiting factory methods to the case where references to subclasses are returned is a worthless restriction. The idea remains the same. However, I realize that my personally opinion should not matter. Esben 10:16, 13 November 2007 (UTC)

text: ACK, the examples are complete junk. The GoF book has a credible example where different kinds of games are created. 130.92.99.77 (talk) 20:40, 5 December 2010 (UTC)
thread_title:  Complex example 

message: My use case of the article is as a reader trying to understand the Factory design pattern in a Java context. As I understand one of the purposes with encapsulating the constructor and use static factory methods in the object creation process to make it clearer wich arguments should be used (Cartesian or polar). However, I think the example is still ambigious as the argumentss can easily be swapped. Both are of the real type, so in principle the user of the creator method could swap, e.g., the real and imaginary part in the fromCartesian method. Would it not be clearer to modify the example into the following?
class Complex 
{
     public static Complex fromRealAndImaginary(double real, double imag) {
         return new Complex(real, imag);
     }
 
     public static Complex fromModulusAndAngle(double rho, double theta) {
         return new Complex(rho * cos(theta), rho * sin(theta));
     }
  
     private Complex(double a, double b) {
         //...
     }
}
  
 Complex c = Complex.fromModulusAndAngle(1, pi); // Same as fromRealAndImaginary(-1, 0)
-- Slaunger (talk) 08:27, 21 November 2007 (UTC)
replies: text: First of all, the language is irrelevant. Second, as for the names of the methods, your examples are much more verbose, and adds very little, since the names of the parameters should tell the user which one is what (in the polar variant, the arguments should be "modulus" and "angle"... I will change that after this. But you do illustrate that the point mentioned above is very valid: The Complex example isn't really a factory (object) example, but an example of "named constructors" which are also sometimes called factory methods. Esben (talk) 08:40, 21 November 2007 (UTC)
replies: text:  Never saw the term "named constructor" before today. The implications of constructors versus factory methods are sufficiently different that I think it's inappropriate to introduce a name suggesting one is a form of the other. 204.60.84.2 (talk) 17:24, 2 February 2012 (UTC)
thread_title:  Complex Java example - would this be an improvement? 

message: I guess that the image describing the factory method pattern :Image:FactoryMethod.svg isn't correct.
According to Design Patterns, the concept that varies in the factory method, is the subclass of object that is instantiated
Which means that the factory method instantiates a concrete ConcreteProduct which inherits from an abstract AbstractProduct.
Thus the figure should show:
* An inheritance relationship between an abstract AbstractProduct and a concrete ConcreteProduct.
* A dependency relationship between the abstract AbstractProduct class and the Creator class (containing the factory method that returns AbstractProduct), the dependency points to AbstractProduct.
* Multiple concrete Product classes can exist in the figure, representing the concept that varies. where the logic for choosing which concrete Product object to instantiate and return, exists in the factoryMethod().
And thus, the inheritance relationship illustrated between the abstract Creator class and the concrete ConcreteCreator class is irrelevant to the design pattern discussed.
Kerdany (talk) 09:55, 19 June 2008 (UTC)
thread_title:  Wrong Image 

message: The first two "limitations" listed are issues arising from making the constructors private. However the page does not stipulate anywhere that the constructors should be made private. The factory pattern works just as well if you do not make the constructors private. Not making the constructors private eliminates those two limitations. (whether or not that is good "style" is another matter) So it seems that those limitations are not inherent to the factory pattern but rather to other design choices. 216.36.186.2 (talk) 18:01, 15 August 2008 (UTC)
replies: text: What's more, some of the examples wouldn't actually work if the constructors were private, the example factory under "Encapsulation" calls the constructors just as any regular code would, if they were private it would give an error (unless it were a friend, but the example is in Java which doesn't support friends).  You could use what I call "package" methods to restrict constructor calling to classes only in the same package, which is where the factory would need to be placed too, but that still breaks this apparent "rule" of private constructors. -- Y Less (talk) 14:25, 6 January 2009 (UTC)

text: Often you use a factory method to provide initialization of properties. If the constructor is visible, instances may be created via constructor calls and these instances would not have the proper initialization. A factory method should *replace* a constructor. 82.176.252.66 (talk) 11:18, 31 January 2009 (UTC)
thread_title:  The First and Second "Limitations" 

message: Can someone explain the difference between the ImageReader encapsulation example provided and the Abstract factory pattern?  They look about the same to me... Thanks. 93.97.156.254 (talk) 09:01, 16 May 2009 (UTC)
thread_title:  Clarification request 

message: The introduction states:
The factory method design pattern handles this problem by defining a separate method for creating the objects, whose subclasses can then override to specify the derived type of product that will be created.
* Whose subclasses is this referring to? method's subclass or object's sublass? In either case, it is technically incorrect because methods and objects do not have subclasses (please correct me if I am wrong), only classes can have subclasses. I think it should be worded differently.
Maybe you are right about wording. It refers to subclasses of the Creator abstract class, as it's defined in the first paragraph of the introduction.
--Klodr (talk) 04:49, 7 January 2013 (UTC)
thread_title:  Clarification Required 

message: Changed the Java example.  Shortened:
class HamAndMushroomPizza extends Pizza {
    private double price = 8.5;
    public double getPrice() {
        return price;
    }
}
to
class HamAndMushroomPizza extends Pizza {
    public double getPrice() {
        return 8.5;
    }
}
Perhaps slightly less idiomatic, but gets across the point more clearly, I think.  If people disagree, feel free to revert it/discuss it.  --Matthew0028 19:12, 3 August 2009 (UTC)
thread_title:  Shortened Java expample 

message: The wording from "If such a class Foo creates another object Dangerous" down to the end of the page including examples, is something i have seen on another website when doing reserach into factory method pattern, as such is this articale not in violation of copyright as no accreditation is given?  —Preceding unsigned comment added by 86.20.151.215 (talk) 09:56, 12 August 2009 (UTC)
thread_title:  Copyright issues 

message: Definition implies that Factory and Factory method are identical.  Why, then, are there two distinct articles?
Clarification: a Factory is a class that only has Factory Methods, usually for the creation of related objects. The GoF's Abstract Factory relates to an abstract factory that describes the creation of related or family objects, that concrete factories will implement.
--Klodr (talk) 04:54, 7 January 2013 (UTC)
thread_title:  Definition of what? 

message: The definition and the UML diagram are consistent in that a sub-class decides on which object to create, however this is inconsistent with the Java example. The PizzaFactory should extend some AbstractFactory and implement its creational method in order to comply with the UML.  —Preceding unsigned comment added by Killerplantsinmyroom (talk • contribs) 17:42, 8 October 2009 (UTC)
thread_title:  Java example doesn't follow the UML 

message: Funny that the Java guys did it right the first time. :P (Update C# example with fixed-point decimals, output stays unchanged.) - Paradrop (talk) 04:11, 27 February 2010 (UTC)
thread_title:  Please don't use doubles to represent money 

message: In Factory design pattern Factory should not extend an abstact Factory, whereas in current diagram ConcreteCreator extends Creator. This makes ConcreteCreator/Creator an Abstract Factory design pattern.
Wrong. An Abstract Factory describes the interface for creation a set of family objects. Sub-classes override these methods to concrete related objects. Factories are a set of Factory Methods. The diagram and article refers to Factory Method Pattern not Abstract Factory.
--Klodr (talk) 04:58, 7 January 2013 (UTC)
thread_title:  UML diagram looks like Abstract Factory 

message: While the private constructor forces you to use the factory, what happens if you use reflection? Shouldn't you be able to see the constructor? Please someone clarify this. Many thanks! 195.78.86.91 (talk) 12:11, 14 June 2010 (UTC)
thread_title:  private constructor works against reflection? 

message: First of all, let me apologize for making a revision without first discussing it here. I'm clearly a newb to the wiki editing realm and I'm a bit embarrassed for not taking the time to investigate the features of the site prior to attempting an update. Also, I'm not an editor and I don't consider myself one, but I do feel strongly about this specific case. My only goal is to help aspiring developers find correct examples to this and perhaps other patterns that I haven't yet investigated.
The reason I feel compelled to revise the C# example is because, though the present example does in fact represent a factory method pattern, it does so in a very poor manner. The first principle violation that I noticed is to the open/closed principle (OCP). This violation takes place in the form of an embedded enum in the actual factory method, which cements a concrete definition of PizzaType inside the factory, thus creating a dependency. That dependency is then propagated throughout the rest of the example like a virus, which once again is a violation of the OCP. 
There are other questionable principle violations, but the point is that it needs to be revised. The code I proposed was modeled after the real world example on the dofactory.com Web site for the factory method pattern. Galestar's comment that it was not a factory pattern is not accurate. If you question whether or not that's a factory pattern, then you're essentially asserting that you do not agree with the current standard definition of a factory method pattern, which is fine, but you might actually be alone in that conclusion. Furthermore, I've yet to hear how my proposed example violates any principles of coding standards or best practices and why it's not a factory pattern. If you're going to reject an edit, you should definitely provide some details as to what drove you to that decision, rather than just stating a general statement like "that's NOT a factory pattern". I don't care who's example you use, just remove the current example at the very least until an agreed upon example can be issued.
I've submitted my arguments to the Wiki Arbitration Committee for further assessment and opinions on this issue since there is clear disagreement.
--Carbonism (talk) 18:53, 30 July 2010 (UTC)
thread_title:  Erroneous C# Example 

message: Do we really need an implementation example in every language under the sun?  This is adding nothing to the article.  I vote for 2 or 3 languages tops, possibly C++, Java, and possibly Python or Perl.  Fell Gleamingtalk 11:20, 24 August 2010 (UTC)
replies: text: No. We only need one example unless a fundamentally different approach is taken in some languages. I'd vote for Java (since it is in many ways the cannonical strongly-typed OO language) or Python (since it is so easy to read). —Ben FrantzDale (talk) 12:10, 24 August 2010 (UTC)

text: I agree the Java example is pretty ugly, and violates the Open/closed principle as per your comments in the section above I didn't edit the example's content at all, I just trimmed the mess of other examples. I can see how using strings rather than enums would be better with regard to the open/closed principle, on the other hand, neither provides compile-time safety... I don't have Design Patterns in front of me; I fort how their example goes. Feel free to celan up the example. —Ben FrantzDale (talk) 13:16, 30 August 2010 (UTC)
thread_title:  Example Insanity 

message: The link for singleton has nothing to do with the discussion at hand. I suggest it be deleted.  —Preceding unsigned comment added by QLineOrientalist (talk • contribs) 17:22, 3 May 2011 (UTC)
thread_title:  singleton? 

message: NEVER call overridable methods in the constructor.  —Preceding unsigned comment added by 195.234.242.6 (talk) 16:26, 16 May 2011 (UTC)
replies: text: "Never" is a strong word. There's nothing wrong with calling an overridable method from a constructor as long as you're aware of the semantics of doing so in your implementation language. 204.60.84.2 (talk) 17:22, 2 February 2012 (UTC)
thread_title:  Java example - a classic example of how things should not be done 

message: This article is 100% class-based. In a prototypal language (JavaScript, for instance) the concerns are very different. Could we approach this from a broader perspective?MartinRinehart (talk) 13:39, 28 August 2011 (UTC)
thread_title:  Prototypal Inheritance 

message: 450px|right|My proposal to be added to the Common usage section
I am a Java programmer, but I doubt that somebody not involved in programming as much as I would understand this section. A UML diagram or a short code should be added. (If you want to make corrections, I can send you the Word document to modify it easily.) Sae1962 (talk) 11:39, 22 May 2012 (UTC)
thread_title:  Common usage section needs clarification 

message: I strongly recommend splitting the article to separate the GoF's Factory Method Pattern of the plain Factory Method.
--Klodr (talk) 05:10, 7 January 2013 (UTC)
thread_title: Please split the article

message: -- Emilhdiaz (talk) 22:42, 12 October 2012 (UTC)
thread_title:  Factory or Builder (Java Example) 

message: Maybe I'm missing something here, but I don't think it's a good idea to save code directly inside PHP classes, and not in methods.  — Preceding unsigned comment added by 137.194.22.198 (talk) 13:26, 9 October 2013 (UTC)
thread_title:  Erroneous PHP example 

message: To quote the article:
"not all uses of factory methods are examples of the factory method pattern – only when inheritance is involved ... is it an example of the factory method pattern.
Where did this particular criterion creep in to the definition? As I understand it, the only reason why the factory method pattern is illustrated with inheritance is that at the time the GoF book was written (1994), this was the only option available to object-oriented languages of the time (C++ and Smalltalk, and subsequently Java). Now that modern OO languages have other ways of implementing factory methods (e.g. lambda expressions, closures, or monkey patching in Python, Ruby and JavaScript) I don't see any reason why these couldn't be considered examples of the factory method pattern as well.
Certainly, making inheritance as a defining feature of the factory method pattern results in confusing and misleading terminology. It effectively states that a method is the same thing as a class hierarchy, which is nonsense; it introduces a counterintuitive and confusing schism between the meanings of the terms "factory method" and "factory method pattern"; and AFAIA it doesn't reflect real-world usage.
At the very least, the article needs to be updated to say who has defined it as such, where, and why, citing a reliable secondary source. Otherwise, that part of the article should be removed. 85.255.235.69 (talk) 17:10, 24 October 2014 (UTC)
replies: text: I agree. Am changing it.--Diaa abdelmoneim (talk) 15:19, 2 January 2016 (UTC)

text: Saying that it 'may' use inheritance after the previous paragraphs say that it does use subclasses is odd. I think the intent of the previous message was to distinguish this pattern from the more general Factory_(object-oriented_programming) concept. On that page there is the complex number example that is used as a named constructor and wouldn't be classed as the factory method pattern because it doesn't defer instantiation to subclasses (or any equivalent). 81.187.215.34 (talk) 18:46, 21 May 2016 (UTC)
thread_title:  Factory method pattern and inheritance? 

message: The limitations section doesn't make much sense now.
They talk about 'code shown earlier' which doesn't exist.
They say that the pattern relies on using a private constructor, when none of the examples do.
The StrangeComplex.fromPolor example seems to be talking about having to reimplement static
methods in subclasses, which again doesn't match the examples.
We should probably rewrite or remove this section. 81.187.215.34 (talk) 18:29, 21 May 2016 (UTC)
replies: text: I've moved this to the factory page because it matches the examples there. 81.187.215.34 (talk) 21:07, 29 May 2016 (UTC)
thread_title:  Limitations 

message: I would like to share the following UML diagram I have published on Design Patterns Open Online Learning. Your comments are welcomed!
In the above UML class diagram, 
the Creator class that requires a Product object doesn't instantiate the Product1 class directly.
Instead, the Creator refers to a separate factoryMethod() to create a product object,
which makes the Creator independent of which concrete class is instantiated.
Subclasses of Creator can redefine which class to instantiate. In this example, the Creator1 subclass implements the abstract factoryMethod() by instantiating the Product1 class.
Vanderjoe (talk) 18:54, 5 August 2017 (UTC)
thread_title:  UML class and sequence diagram 

message: A recent edit  added Delphi implementation.   I'm just curious what the selection criteria for example implementations is?  Delphi is #17 on TIOBE.  All of the other implementations were 5 of the top 8.  Adding Delphi might then mean we should add 11 more languages. Galestar (talk) 15:10, 21 June 2019 (UTC)
thread_title:  Language Implementations 

message: It's not very helpful to start with a description of a game class model first and using a complete different example for php second. It does not show the advantage of the factory pattern over traditional class inheritance at all, because it shows just one class with one factory. --84.167.187.209 (talk) 13:14, 11 May 2021 (UTC)
thread_title:  PHP example does not corrospond to other examples