Win a copy of Terraform in Action this week in the Cloud forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

Factory Method Pattern usage in Java JDK

 
Ranch Hand
Posts: 59
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

I know how Factory Method Pattern works, but what i wanted to know is it's real time usage in Java JDK.
Where it is used in java API?

Thanks in advance.
 
Marshal
Posts: 74388
334
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Most of the wrapper classes have their constructors deprecated, so the usage is no longer new Integer(123) but IntegervalueOf(123).
Most of the types introduced in the date time and Streams API have factory methods and private constructors, so the following usages would be impossible:- new Optional<String>("CodeRanch"), new IntStream(1, 2, 3), and new LocalDate(2021, 11, 7). In all cases the usages use the of() method:-- Optional<String>.of("CodeRanch"), IntStream.of(1, 2, 3), and LocalDate.of(2021, 11, 7). In all these cases the usages use the of() method, and I am not sure I have got the Optional example right.
 
vishnu priyag
Ranch Hand
Posts: 59
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:Most of the wrapper classes have their constructors deprecated, so the usage is no longer new Integer(123) but IntegervalueOf(123).
Most of the types introduced in the date time and Streams API have factory methods and private constructors, so the following usages would be impossible:- new Optional<String>("CodeRanch"), new IntStream(1, 2, 3), and new LocalDate(2021, 11, 7). In all cases the usages use the of() method:-- Optional<String>.of("CodeRanch"), IntStream.of(1, 2, 3), and LocalDate.of(2021, 11, 7). In all these cases the usages use the of() method, and I am not sure I have got the Optional example right.



But i didn't see any of the classes/interfaces mentioned above matches the Factory Method Pattern definition.
Factory Method Pattern defines an interface to instantiate an object, but lets the sub classes decide what objects need to be instantiated. Factory method pattern lets the class defer to sub classes for object instantiation.

I want to know java API classes following this definition.
 
Saloon Keeper
Posts: 1658
61
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The names of the Design Patterns get annoying here.

I believe that several of the common sources will describe what Campbell gave as examples as a Simple Factory Pattern, but many won't!

Even the Simple Factory Pattern lets one method return one of several possible sub-classes that share a common interface or base class.
https://catsincode.com/simple-factory-design-pattern-java/

We should probably use the definition of Factory Method Pattern from here since the terminology gets tricky:
https://en.wikipedia.org/wiki/Factory_method_pattern

This page tries to describe the distinction between Factory Method Pattern and Factory Pattern:
https://www.c-sharpcorner.com/UploadFile/akkiraju/factory-design-pattern-vs-factory-method-design-pattern/

(sorry for the C#)

While everyone agrees that the examples provided by Campbell are indeed "factory methods" I don't think they are examples of the Design Pattern with the name "Factory Method Design Pattern".

Note, normally I am the guy who is all hung up on what names we call things, it is often annoying, but it is sometimes important so we can be sure we are talking about the same things when we are using the same words.

I don't at the moment have a good example of "Factory Method Design Pattern" examples in Java JDK, but someone will probably come up with one soon.
 
Jesse Silverman
Saloon Keeper
Posts: 1658
61
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I believe that we would need to have more insight into the code implementing the various JDK classes than most of us normally do to answer this properly.

For example, it seemed plausible to me that LocalDate.of() might be one of these, so I went and looked and would say "Nope, doesn't seem to be a valid example of Factory Method Design Pattern":



It does some nice checks and then calls another static method IN THE SAME CLASS which does some more nice checks and then calls the classes own private constructor:




All of this is wonderful, fantastic and good for me as a developer, but fails as an example of the "Factory Method Design Pattern in the JDK" because it is not one.

I haven't found one that matches the formal definition yet, but as I am not usually looking at their implementations, but just their JavaDocs am not going to find that very quickly.

 
Jesse Silverman
Saloon Keeper
Posts: 1658
61
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Is List.of() an example of what the poster is looking for?

I am not sure, I got into deep water fast...calling a static factory method in another class:



That function gets into even deeper water quickly, but seems to be deciding itself which explicit constructor to call:


Maybe it is.  The user code is just calling the List.of() method with no clue of which of various constructors that she doesn't even know the name of will ultimately be called.   Of calls method ImmutableCollections.listFromTrustedArray() which the user doesn't even know the name of.
That factory method then decides based on criteria not known to the user which constructor to call (the names of which are also unknown to almost every user) or whether to return a static element of EMPTY_LIST;

So maybe List.of() qualifies because decisions about which constructor (if any) to call are made based on factors unknown to its caller.

Of course Integer.valueOf() also decides whether or not it needs to call a constructor, but based on a factor the user is aware of.

I'll leave off trying to help further for now, having learned some more about the implementation of some standard "factory methods" in OpenJDK 17 than I knew previously, but maybe not enough to answer definitively.
 
Jesse Silverman
Saloon Keeper
Posts: 1658
61
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I've been researching links to Java-specific Design Patterns sites while cleaning up our Links page.

Many of the links I have added are great ways to learn Design Patterns, but the only one that I see directly answering your question is here:
https://java-design-patterns.com/patterns/factory-method/

Feedback on the quality of both information and the presentation of that information on those sites is appreciated.
 
Campbell Ritchie
Marshal
Posts: 74388
334
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I am not sure about that as a brilliant example of a factory method. If there is a factory method, it is in the XYZARSENAL classes, or even in the enums passed as arguments to the manufactureWeapon() method. My view of a factory method is that it creates and returns an instance of the class on which it is called. [It might not create an instance every time, or even create an instance at all, if a suitable reusable instance already exists.] That link also looks out of date if they are quoting java.util.Calendar as an example of a class with factory methods rather than LocalDate, etc, even though those links appear to use Java8.
Also those methods are specified in an interface, so they are instance methods, and most factory methods I have seen are static. You can nowadays have static factory methods in interfaces, e.g. this method.
 
Campbell Ritchie
Marshal
Posts: 74388
334
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Maybe, as stated earlier, the problem is that the structure of the pattern and the method with the same name are different.
 
Jesse Silverman
Saloon Keeper
Posts: 1658
61
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Campbell!

I am not sure, because I am still in the throes of getting very comfortable with the Creational Design Patterns, but:

I think it is an unfortunate lexical coincidence that Java calls their functions "methods" and that there is a particular Design Pattern named "Factory Method Pattern" that applies to all Object-Oriented languages, whether they call their functions "methods" or not.

There are a few different Creational Patterns that have the word "Factory" in their titles, the differences are subtle, but real.

There are numerous ways of getting an object without calling a constructor that are indeed presented as "methods" in Java.

Several of them have been ret-conned to "Simple Factory Method" in newer writings attempting to be precise.

I'm still confused enough not to say more, but I feel pretty sure about what I wrote so far.
 
Jesse Silverman
Saloon Keeper
Posts: 1658
61
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Again, not sure, but I think that this is the key to whether something is the "Factory Method Pattern":

someone quoted earlier wrote:Factory Method Pattern defines an interface to instantiate an object, but lets the sub classes decide what objects need to be instantiated. Factory method pattern lets the class defer to sub classes for object instantiation.

 
Campbell Ritchie
Marshal
Posts: 74388
334
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, I think I am getting confused about the terminology.
 
Saloon Keeper
Posts: 24575
168
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
One thing to bear in mind is that there are no absolutes in Design Patterns. There are no Universal Patterns, different people may posit similar-but-not-identical patterns, names may vary. There were some JEE design patterns that are actually obsolete. The JEE Data Transfer Object was never anything but a hack anyway and EJB3 made the need for a separate staging object unnecessary.

Here are some common Factory implementations:

* Spring Framework
* JavaServer Faces Managed Beans - deprecated in favor of CDI
* JEE CDI

Possibly you can find an Entity Manager Factory within JPA as well, although I've not looked.

Additionally we see object-specific factories as Campbell has noted in the deprecation of constructors for many of the basic Java data types, such as Integer valueOf.

Factories can be subdivided into two major types: Pure Factories and Factory/Warehouse factories. A Pure factory returns a unique object every time it's called. A Factory/Warehouse keeps an internal inventory and if it has already constructed an object, returns that object (as a singleton instance). Some factories, such as Spring, can operate both ways, although by default Spring delivers in Factory/Warehouse mode.

Incidentally, one reason for the deprecated status for basic value constructors is that the "valueOf" methods are Factory/Warehouse methods, unlike the operator-new construction process. For example, Integer keeps a warehouse with popular values in it such as 0, 1, -1, and sometimes others (the exact collection may be subject to the implementor's whims and/or standards versions). So instead of littering the object space with potentially thousands of Integer(0)'s, we can have only one, since it's immutable. Doesn't mean it's safe to assume that two Integer.valueOf (0) results obey the "==" comparison, but it can be a big help in optimal storage usage.
 
Jesse Silverman
Saloon Keeper
Posts: 1658
61
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I've been reading thru our historical discussions on these topics from (way) before I was a regular.

There used to be far more discussion of these topics here, but I don't think the ideas have become less important.

Long ago, over here:
https://coderanch.com/t/99278/engineering/pattern-vote-island

Ilja Preuss wrote:Actually not, no. A creation method typically is static, whereas a Factory Method has to be an instance method, because it needs to be called polymorphically. Typically the factory method is declared abstract in the class it is used in and defined in subclasses (it is a specialization of the Template Method pattern).



There's a lot of interesting stuff in that thread, along with some hub-bub and noise...
 
Jesse Silverman
Saloon Keeper
Posts: 1658
61
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Some more choice quotes that squarely aim at erasing confusion I've been party to recently...

Ilja Preuss wrote:Certainly the term Factory Method is already defined by GoF, in a way that doesn't allow a Factory Method to be a simple static method. So it seems clear to me that if we mean a static method that creates things, we should use a different name for it...


...

David Hibbs wrote:No, just being a little bit antagonistic  -- and point out that by pure GoF names, there is no name for a static creation method. Call it whatever you want, but I call it a factory (especially if you pass it a parameter to indicate what you want). Judging by the Apache code, I'm not the only one.
...
1) We agree (I think) that this is a pattern of some sort.
2) We agree (Again, I think) that this is a creational pattern.
3) Limiting scope to GoF terms, that means it must be one of Abstract Factory, Builder, Factory Method, Prototype, or Singleton.
4) Rule out Builder and Prototype.

This means it must be one of Abstract Factory, Factory Method, or Singleton.

It could be a Singleton, but there is no guarantee. Barring Singleton, a static creational method then must be a Factory of some sort. Perhaps we could call it a Simple Factory ?



I don't know if the various places I have now seen agreeing to use the "Simple Factory" term all trace back to this CodeRanch quote, but they might.  Either way, I agree, people in the future (of 2005) are still going to be reading and discussing GoF and minimizing "naming clashes" is of value towards reducing confusion.

Arguably, the most important part of Design Patterns is facilitating communications between people.

 
Jesse Silverman
Saloon Keeper
Posts: 1658
61
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Maybe it would be helpful to name something "Simple Factory Pattern" but not necessary, because it can be considered a variant of Factory Method Pattern after all (I note that overly-overloaded terms can sometimes be confusing to many, however).

I was certainly getting confused reading presentations by apparently highly-competent sources using different names for the same things, personally.

I am not sure here yet, because I am still reading up on it here (actually in the free .PDF formatted book, but the website is the same except where it has newer revisions):

https://w3sdesign.com/

w3sdesign wrote:Note that the Factory Method pattern can be implemented differently (abstract, concrete, or static factory method). See Implementation.



The number of references to Effective Java is high, so consider this a point in favor of this site as a reference if you are a Joshua Bloch fan.  It seems nothing that is covered on this site which is also covered in that book is treated without a mention of what that book seems to say about it (2nd edition thru-out, the content was mostly prepared before the release of the third edition).

There are also lots of references to other authoritative works as well, their emphasis is on getting all relevant information in one easy-to-use place, rather than showing off lots of Original Ideas.

I absolutely love the design of this site for interactive use, but find it slightly difficult to point others towards specific sub-sections.

Anyone interested can go to the site, and note that the "Factory Method Pattern" is the third one in the first row, which are all the GoF Creational Patterns.
 
Tim Holloway
Saloon Keeper
Posts: 24575
168
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You might find this interesting. This is the primary Factory Interface for the Spring Framework and its AutoDocs explain what sorts of Design Patterns it facilitates:

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/BeanFactory.html

Because it's an Interface, the getBean methods are necessarily member methods, but in any event, Spring supports many different types of Bean Factories up to and including roll-your-own, so it's best to address the factory as a generic instance and not by absolute (class) reference.

Jesse Silverman wrote: Arguably, the most important part of Design Patterns is facilitating communications between people.



And yes, I'll argue it. The most important part of Design Patterns is that they are proven workable abstract architectures that can be easily implemented on virtually any language and (in many cases) platform. That means no need to design from scratch and debug from scratch. Having such architectures publicly documented means that people can communicate about them in a common language, but the essential part is having a known and proven basis to implement specific functionality.
 
Marshal
Posts: 26914
82
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here's an example of your Simple Factory pattern:

Way back in 2005 I started to write a large Swing application to maintain a database which I own and support. This was a rewrite of a Turbo Pascal program, driven mainly by the advent of SQL databases but also by the need to support more geographic locations and by my interest in learning Java.

So like anybody else writing a Swing application I wanted to standardize the appearance of the GUI in a way which differed from the way standard Swing GUIs appeared -- panel backgrounds should be white, text should be in a particular font, and so on. Naturally I wrote subclasses to do that: my subclass of JButton had a setFont() call in the constructor but it didn't change any other behaviour of the button.

This wasn't much different that a lot of things the Swing architects had already done, but I noticed a lot of people on the forum complaining about subclasses which didn't behave differently from their superclass. So I rewrote those things as factory methods. A static factory was fine, all it had to do was e.g. create a JButton, call setFont() on it, and return the JButton. That's a Simple Factory.

(And yes, a lot of the Swing architecture is now out of fashion due to both advances in the language and broader knowledge of architectural principles. Things like implementing SwingConstants so you could write EAST instead of SwingConstants.EAST in your code -- nowadays you would have some Enums for those constants and you'd use "import static" to simplify using them.)
 
Jesse Silverman
Saloon Keeper
Posts: 1658
61
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Paul Clapham wrote:
(And yes, a lot of the Swing architecture is now out of fashion due to both advances in the language and broader knowledge of architectural principles. Things like implementing SwingConstants so you could write EAST instead of SwingConstants.EAST in your code -- nowadays you would have some Enums for those constants and you'd use "import static" to simplify using them.)



I am focusing on the Wrong Part again, but this reminds me of the last week I was working in Python every day.

I was playing about with TKINTER, and guessed that I could have some code near the start swap EAST, WEST, NORTH, SOUTH etc. just for kicks, because we are all consenting adults and constants are just constants until they change.

The expected results were achieved, upside-down inside-out mirror GUI behavior....hilarious.
 
Jesse Silverman
Saloon Keeper
Posts: 1658
61
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There is a good post on StackOverflow that addresses Classic GoF patterns in the Java JDK:
https://stackoverflow.com/questions/1673841/examples-of-gof-design-patterns-in-javas-core-libraries

Unfortunately for our current thread, the main point brought up by critics of the best-accepted answer is that since Simple Factory is really not an original GoF Pattern, some of those examples for Abstract Factory should be categorized together with Factory Method Pattern.

I think this demonstrates that one of the most common mapping difficulties to the Classic set of GoF patterns to how we use them (and the terms) in Modern Java is right here with these.

Extremely knowledgeable people seem split on whether it is better to consider "Simple Factory" a simplification of Abstract Factory or of Factory Method...
 
Tim Holloway
Saloon Keeper
Posts: 24575
168
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well, as I said before, Design Patterns are not absolutes, and the Gang of Four neither invented them nor are the sole authority for them. They discovered and documented patterns and made a formal discipline of it, but the patterns had been in use for time immemorial and there are more to be created and discovered all the time.

Design Patterns are a discipline rather than a concrete entity and they're inherently fuzzy. It's why no one has created an overpriced Silver Bullet tool for generating code from patterns. It's not unexpected that there can be controversy. Linnaeus developed biological classifications quite a long time ago and every day people argue where to put species. And plants and animals and their DNA are much more concrete than software designs.
 
Jesse Silverman
Saloon Keeper
Posts: 1658
61
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Your point is well-taken, as is the earlier point that the important qualification for them is that they solve a real need, well.

I am still a little hung-up on hoping everyone uses terminology consistently secondarily to reduce chatter of "Oh, you call it that?  I would call it this?" and primarily so that after a brief conversation where we both think we understand what was said, you or I don't go off for three hours and implement something different than what the other one wanted/needed/expected.

Given how they are patterns, not recipes, I am generally impressed that for the most part, people are using terminology consistently.

The thing of what to call Simple Factories is fortunately a bit of an exception.

One more thing on terminology.

I have reviewed threads from here in the long past where people vigorously argued over whether "Encapsulation" only meant data and code living together inside a class, or it also included the information hiding and separation of data/implementation and interface.

I note that in the GoF book, they very clearly and unambiguously use the term to mean the latter, which is to say a class that contained all relevant data and methods but left them all public would NOT be said to be encapsulated.  So at very least by 1994, people had been using that term in its stronger meaning in very popular material.
 
Jesse Silverman
Saloon Keeper
Posts: 1658
61
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yeah, there's no absolutes, not everyone agrees on terminology, the important thing is that you know how to do good design, etc.

But I am still interested in finding common ground on terminology so everyone can communicate effectively.

It turns out that those who knew GoF very inside-out but have kept up with the changing times say this:

An increasingly popular definition of factory method is: a static method of a class that returns an object of that class' type. But unlike a constructor, the actual object it returns might be an instance of a subclass. Unlike a constructor, an existing object might be reused, instead of a new object created. Unlike a constructor, factory methods can have different and more descriptive names (e.g. Color.make_RGB_color(float red, float green, float blue) and Color.make_HSB_color(float hue, float saturation, float brightness)



From:
https://sourcemaking.com/design_patterns/factory_method

Joshua Bloch may use similar terminology, someone with the 3rd edition of Effective Java could check for sure.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic