• 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:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Regarding static factory method and constructor

 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Friends,

can you explain to me,what is difference between static factory method and constructor? and what are the advantages over constructor?
 
Ranch Hand
Posts: 449
Scala IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
See this sample chapter of Effective Java. It would provide nice explanation to your query.
 
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

praveen raaj wrote:
can you explain to me,what is difference between static factory method and constructor? and what are the advantages over constructor?



The difference is that a constructor is a Java language element whereas a factory method is a design pattern you apply. But both regards object construction. Each time an object is created a constructor of the class will be run.

One of the most common usages of a factory method is to increase encapsulation, like here,


The interface and the factory method are defined somewhere in a package. They're often the only things public in the package. The rest is implementation classes and stuff hidden within the package. So the only thing a user sees is the I interface and the create method. It's very easy to modify what concrete objects the create method returns. And the nice thing is the this doesn't change any code using I and create.

By doing this you've got a clean separation of a type (the I interface) and its implementations (the A, B objects).

The create method can be made more complex. For example by providing a parameter to create a user may be able to control which variation of I is to be returned (A and B could be slighty different in some respect).
 
reply
    Bookmark Topic Watch Topic
  • New Topic