Jump to content

Talk:Factory method pattern

Page contents not supported in other languages.
From Wikipedia, the free encyclopedia

What's the advantage?

[edit]

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)[reply]

Try writing the Complex class example in the article, and you will see the advantage. Esben (talk) 18:28, 6 February 2008 (UTC)[reply]

@OP- dude, you are missing the point. obviously. Just reread your own post. Better? that is not the issue. They are two completely different actions. To call a constructor, correctly paramaterized or otherwise, requires a reference to implementation. A factory allows you to code to an interface and promotes agility. Fundamentals are a good thing. They help you understand things. ;-)Bitpusher (talk) 06:59, 26 August 2009 (UTC)[reply]

@OP - The short answer is this: In cases where a two different constructors make sense but their parameter lists are identical, the compiler/interpreter has no way to identify which one you mean when you try to instantiate that object in a way that would invoke a constructor with that parameter list. This technique is a way to get around that by forcing you to specify which 'constructor' behaviour you mean using specifically named functions that stand in place of the traditional constructors.

That said, @Bitpusher - I have to call out that comments like yours are not helpful at all, and in their way even worse. OP asked an honest, intelligent question and was met with belittling that did nothing to clarify the issue at hand. Both constructors and this pattern allow the object's user to "code to an interface." In one case it's an interface whose exposed API happens to include a method named Object::Object(double, double) and is implicitly called on instantiation, and in the other it's an interface whose exposed API happens include a method named Objects::fromCartesian(double, double) that must be called explicitly. Neither escapes the necessity for a (nebulously defined) "reference to implementation." Next time, feel free to offer insight rather than parroting back the contents of your Agile Pattern Synergies for Dummies book and condescending to people who are attempting to actually understand the subject. And no, adding a ;-) symbol does not make it okay to be a prick. —Preceding unsigned comment added by 67.217.89.1 (talk) 16:34, 2 September 2009 (UTC)[reply]

Article doesn't really describe the GoF pattern?

[edit]

Sorry for butting in but the article doesn't actually explain anything. If one is a newcomer it doesn't make any sense. For those who already know it, there is no need for the article ... Bill. —Preceding unsigned comment added by 220.233.122.121 (talk) 13:39, 26 November 2007 (UTC)[reply]

Please do not merge this into Factory (Software Concept). Those who are unfamiliar with Object Oriented Design can look at the title and see that, there are many design patterns in Object Oriented designs and this is one of them. --Joji

I want to echo Joji's comment. The Factory Method pattern is a very specific GoF pattern. Many instances of factories are not implementations of the GoF Factory Methods pattern. It' s important to have separate articles on factories in general vs the GoF pttern. — Preceding unsigned comment added by 71.72.54.28 (talk) 03:24, 18 February 2013 (UTC)[reply]

Also agree, do not merge. — Preceding unsigned comment added by 66.210.101.130 (talk) 18:56, 13 June 2013 (UTC)[reply]

Factory method pattern is a creational pattern and there is nothing being created in example. A call to getPrice() is just an example of virtual/overridden method. Sameergn (talk) 00:34, 8 March 2009 (UTC)[reply]

In my understanding, the GoF Factory Method pattern is much more specific than the description in the article. It is like a specialization of the Template Method pattern - the methods defined in the subclasses are actually called in the base class and not part of the public interface.

I agree on this point. This article describes what is often referred to as the Simple Factory, which is not regarded as a first class pattern, but rather a programming idiom. See Head First Design Patterns, O'Reilly for details. —Preceding unsigned comment added by 90.196.44.78 (talk) 15:56, 7 March 2009 (UTC)[reply]

Most of the article seems to be describing something more along the ways of the Abstract Factory pattern, a specialization of the Strategy pattern, where the methods defined are meant to be called by clients outside the class hierarchy.

The "Descriptive Names" example, on the other hand, seems to describe neither Factory Method, nor Abstract Factory, as both those patterns rely heavily on polymorphism. They are more of what Joshua Kerievsky calls "Creation Methods" in his book "Refactoring to Patterns".


Most of the examples u have shown is in c++,java , currently i am working on .net platform, can you put some examples in .net , so i will have more clear view!

.NET is not a language; as you said, it is a platform. However, Java is very similar to C# to the extent that these examples probably make sense just fine in the context of C#. If you were asking for VB.NET examples, well, please learn to read other languages. It's always sad to see developers that eternally stick themselves in VB land. --130.127.53.144 (talk) 15:59, 13 March 2008 (UTC)[reply]

I disagree. There's certainly nothing wrong with requesting (or adding) an example in one's favorite language. An example in .NET could be any of C#, VB.net, or C++/CLI. I agree that Java and C# are similar, although subtle differences exist. decltype (talk) 00:39, 8 March 2009 (UTC)[reply]

If one cannot be bothered to become familiar enough with other dialects to infer something as fundamental as patterns I would submit that one should find other work. Bitpusher (talk) 06:51, 26 August 2009 (UTC)[reply]

Well, to understand pattern roughly - UML diagram is enough, to get the nuances of implementation being "familiar with other dialects" is certainly not enough. Mind you, some implementation in Python will be quite different from C# implementation. To add up to point: example code provided really confuses GoF's Factory Method Pattern with Simple Factory idiom - the fact becomes more obvious if one is really familiar with the language, and doesn't have just "read only" knowledge.
(Almost?) All of the examples incorrectly show a Simple Factory, rather than a Factory Method Pattern. I am going to correct the C# example. If anyone has a problem with this, please discuss. —Preceding unsigned comment added by Galestar (talkcontribs) 18:02, 30 July 2010 (UTC)[reply]
C# example has been reverted. VB.Net example has been added. —Preceding unsigned comment added by Galestar (talkcontribs) 18:56, 30 July 2010 (UTC)[reply]

This article is bullshit. Look at the german version, thats GoF. — Preceding unsigned comment added by 194.114.62.125 (talk) 10:52, 3 November 2014 (UTC)[reply]

Games comment

[edit]

I don't think the extra paragraph on games in 'Comon Usage' adds anything to the article at least not in it's current form, so I've commented it out...

ImageReaderFactory::ImageReader returns pointer not value

[edit]

ImageReaderFactory::ImageReader is declared to return a value (object of class ImageReader) but actually returns a pointer.

ups.. my fault. seems it's supposed to be Java.

Is this C++ ?

[edit]
  • If it is, then code should be more C++-like. Otherwise you should state that this is a Java piece of code.

Consider the following code:

 class Complex
 {
 public:
   static Complex fromCartesian(double real, double imag)
   {
     return new Complex(real, imag);
   } 
   static Complex fromPolar(double rho, double theta)
   {
     return new Complex(rho * cos(theta), rho * sin(theta));
   }
 private:
   Complex(double a, double b)
   {
     //...
   }
 };

 Complex c = Complex::fromPolar(1, pi); // Same as fromCartesian(-1, 0)

The third limitation

[edit]

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)[reply]
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)[reply]
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)[reply]
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)[reply]
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)[reply]

Misunderstanding in Citation

[edit]
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)[reply]

Complex example

[edit]

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)[reply]

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)[reply]

In fact, there reason that it's not the Factory Method pattern is that the methods aren't polymorphic. They are simple static creation methods. --91.89.4.151 (talk) 12:37, 3 July 2009 (UTC)[reply]

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) [reply]

The article badly mixed different concepts. All examples are wrong. A plain factory method is another kind of factory solution to creation of objects, that are implemented usually in named constructors. The GoF's Factory Method Pattern use an abstract field of the Creator abstract class, in an abstract Product (missed in the UML example), and allows the implemented Creator subclasses to define the concrete Product to deliver. A concrete Product then use the concrete Creator using dynamic-binding. All examples presents factory methods, but not the GoF factory method pattern. --Klodr (talk) 04:22, 7 January 2013 (UTC)[reply]

Complex Java example - would this be an improvement?

[edit]

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)[reply]

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)[reply]
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)[reply]

I think having examples in a couple of the most popular programming languages would be helpful for a number of reasons. First, it shows the disparity of languages and brings understanding how different languages handle abstract class, etc. Secondly, it allows for the dissemination of coding technique sharing a peer reviewed, proper usage of the design pattern in that particular language. I would like to see the examples return. —Preceding unsigned comment added by Hradek (talkcontribs) 22:13, 20 April 2009 (UTC)[reply]

-- Emilhdiaz (talk) 21:28, 12 October 2012 (UTC) This example is indeed not a representation of the Factory Method Pattern. As explained before, these are static creation methods. However, this section doesn't really try present these as examples of the pattern itself. This example is under a section for Other Benefits and Variants, which I believe was originally aimed at describing variants that may appear to be similar to the Factory Method Pattern (although a poor approach to it, IMHO). This section should more clearly compare/contrast these variants to the pattern itself to add value to the article. I've moved the section to a lower position in the article to allow proper examples of the pattern itself to surface earlier in the article, in the hopes that individuals new to the subject will be less confused when reading. I've also provided an alternate PHP example to the previous one, as this one was also not a representation of the pattern, but rather another variant ( this variant is also referred to as the Simple Factory ).[reply]

Wrong Image

[edit]

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)[reply]

from the article itself --> "The essence of this pattern is to "Define an interface for creating an object, but let the classes that implement the interface decide which class to instantiate" The relation between the Abstract Factory and Concrete Factory is required by the pattern. The factories could produce the same concrete product with different features. I agree that an ideal diagram would show a family of products - I think the diagram - http://apwebco.com/gofpatterns/creational/FactoryMethod.html covers all aspects correctly. — Preceding unsigned comment added by SamMercs (talkcontribs) 05:34, 28 October 2012 (UTC)[reply]

Kerdany Your second point about the dependency between the AbstractProduct and the Creator is wrong. The dependency in the diagram is correct. The AbstractProduct doesn't depends of the concrete Creator sub-classes of course, because that invalidates the dynamic binding to any other concrete Creator. See GoF Design Pattern diagram and explanation pp. 107-116. The UML only missed the AbstractProduct class and its relation (aggregation) with the AbstractCreator. --Klodr (talk) 04:35, 7 January 2013 (UTC)[reply]

Wrong image

I second the statement that Image:FactoryMethod.svg isn't correct. Or to be precise: It's not how the GoF presented it. I have the Design Patterns in front of me right now and there are 4 items in their image:

  • (abstract) Product ... missing in the image
  • ConcreteProduct (implements Product) ... wrongly named "Product" in the image
  • (abstract) Creator containing FactoryMethod() and OtherOperation(), the latter having a comment with the (pseudo)code snippet product = FactoryMethod() attached to it
  • ConcreteCreator (extends Creator) pointing to ConcreteProduct and containing FactoryMethod() that has a comment with the (pseudo)code snippet return new ConcreteProduct attached to it

The image is also wrong in another respect: How is the (abstract) Creator supposed to know the (concrete) Product to be able to return it from its abstract factoryMethod()? These entitites conceptually reside on totally different layers. And if one looks closely at the image the Product returned from Creator.factoryMethod() is italic. This is for a reason. It alludes to the (abstract) Product that's missing in the image.

It's a shame that this is here in WP apparently since 2013. My suggestion is to correct it accordingly and remove it form here as long as this isn't done. --Gerold Broser (talk) 08:05, 18 September 2015 (UTC)[reply]

The First and Second "Limitations"

[edit]

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)[reply]

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)[reply]
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)[reply]

Clarification request

[edit]

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)[reply]

Clarification Required

[edit]

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)[reply]

Shortened Java expample

[edit]

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)[reply]

[edit]

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)[reply]

Definition of what?

[edit]

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)[reply]

Factory Method pattern is a pattern defined by GoF that creates objects in a factory method that is overridden in derived concrete creator classes. There can be many other ways to implement factories, such as simple factory objects. However, these factories don't implement the GoF Factory Method pattern. — Preceding unsigned comment added by 71.72.54.28 (talk) 03:32, 18 February 2013 (UTC)[reply]

Java example doesn't follow the UML

[edit]

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 (talkcontribs) 17:42, 8 October 2009 (UTC)[reply]

the csharp example has the same exact problem. —Preceding unsigned comment added by 63.99.207.1 (talk) 23:20, 9 July 2010 (UTC)[reply]

Please don't use doubles to represent money

[edit]

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)[reply]

UML diagram looks like Abstract Factory

[edit]

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)[reply]

private constructor works against reflection?

[edit]

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)[reply]

Erroneous C# Example

[edit]

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)[reply]


Well it looks like after some discussion Galestar agrees with me. Whether or not my example should be used should still be up for debate. I've actually discussed this with some of my colleagues as well and they agree that the previous example needed to be modified.

--Carbonism (talk) 19:07, 30 July 2010 (UTC)[reply]

Current C# example doesn't actually show a Factory in use at all. Java example should be ported to C#. —Preceding unsigned comment added by 203.59.228.172 (talk) 08:31, 20 August 2010 (UTC)[reply]

Example Insanity

[edit]

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)[reply]

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)[reply]

Oh dear. That Java example is pretty much the same nonsense as the other C# example was. This is why Wiki has such a bad reputation. Carbonism (talk) 23:29, 27 August 2010 (UTC)[reply]

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)[reply]

"Do we really need an implementation example in every language under the sun?" "No. We only need one example unless a fundamentally different approach is taken in some languages." We only need one example, but it must be in a language in which the reader is fluent. Java's fine for me. Visual Basic works for many. Larry Wall might have another idea.MartinRinehart (talk) 13:31, 28 August 2011 (UTC)[reply]

singleton?

[edit]

The link for singleton has nothing to do with the discussion at hand. I suggest it be deleted. —Preceding unsigned comment added by QLineOrientalist (talkcontribs) 17:22, 3 May 2011 (UTC)[reply]


Java example - a classic example of how things should not be done

[edit]

NEVER call overridable methods in the constructor. —Preceding unsigned comment added by 195.234.242.6 (talk) 16:26, 16 May 2011 (UTC)[reply]

"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)[reply]

Prototypal Inheritance

[edit]

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)[reply]

Interesting proposal. Why don't you write some additional example? Maybe in another section showing another approach. In the case of the GoF's original Factory Method Pattern, they only use class inheritance, but I suppose the implementation is possible with other OO languages that use prototyping.

--Klodr (talk) 05:04, 7 January 2013 (UTC)[reply]

Common usage section needs clarification

[edit]
My proposal to be added to the Common usage section
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)[reply]

Please split the article

[edit]

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)[reply]

Factory or Builder (Java Example)

[edit]

-- Emilhdiaz (talk) 22:42, 12 October 2012 (UTC) The Java example of the Factory Method Pattern is a bit vague and can easily be confused for the Builder Pattern. I know this example is essentially a Builder that makes use of a Factory Method, but I think for individuals new to the subject and looking for information, this makes the learning experience more difficult than it needs to be. I vote we provide a simpler example closer to the pure GoF definition of the pattern (perhaps more in line with what I provided in the PHP example). Optionally, we can show this current example as a way to illustrate how Factory Method and Builder can be used together. Thoughts?[reply]

Current Example:

public class MazeGame {
  public MazeGame() {
     Room room1 = makeRoom();
     Room room2 = makeRoom();
     room1.connect(room2);
     this.addRoom(room1);
     this.addRoom(room2);
  }

  protected Room makeRoom() {
     return new OrdinaryRoom();
  }
}
public class MagicMazeGame extends MazeGame {
  @Override
  protected Room makeRoom() {
      return new MagicRoom();
  }
}

Erroneous PHP example

[edit]

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)[reply]

I think I fixed this now :) — Preceding unsigned comment added by Matthewhaworth (talkcontribs) 11:29, 24 October 2013 (UTC)[reply]

Factory method pattern and inheritance?

[edit]

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)[reply]

I agree. Am changing it.--Diaa abdelmoneim (talk) 15:19, 2 January 2016 (UTC)[reply]
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)[reply]

Limitations

[edit]

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)[reply]

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)[reply]

UML class and sequence diagram

[edit]

I would like to share the following UML diagram I have published on Design Patterns Open Online Learning. Your comments are welcomed!

A sample UML class diagram for the Factory Method design pattern.

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)[reply]

Language Implementations

[edit]

A recent edit [1] 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)[reply]

PHP example does not corrospond to other examples

[edit]

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)[reply]