Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Singaton pattern and factory pattern  RSS feed

 
bhaveshs shah
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sir,

Kindly explain How to use Singaton pattern and factory pattern using Java,JSP,Servlet,artechure?

Thanking You

Bhavesh
 
sachin yadav
Ranch Hand
Posts: 156
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A singleton patteren says "Only one instance per class" i.e. you will always get the same instance of the class, no other instance will be created. One way of doing this is:



here we simply made the constroctor as private so that no one can dirctly initalize our class, now we will always call the getInstance() method to create the instance of our class, where we will check if the class is intantiated earlier or not and return the instance of the class.

I hop this will be helpfull.


 
Deepak Bala
Bartender
Posts: 6663
5
Firefox Browser Linux MyEclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use google
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by bhaveshs shah:

Kindly explain How to use Singaton pattern and factory pattern using Java,JSP,Servlet,artechure?


Can you please clarify your doubts? What do you know about those patterns, and what do you want to use them for?
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To nitpick a bit ... Sachin's example is not thread safe - the JVM could switch threads between the if clause and the new Singleton clause. Since you mentioned JSP and Servlet which are multi-threaded environments, that could be important.

If so, there are a couple very easy ways to fix it up. One is to make the getInstance() method synchronized. Then only one thread can be in there at a time. The other is to create the instance with the declaration

That reduces the getInstance() method to a single line "return".

To the original question ... The getInstance() method is a creational method ... a way client objects can get an instance of something other than the new keyword. It's not quite any of the factory related patterns in the Gang of Four book, but it's on the way there.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!