Please also explain Factory class too.
Actually I have the same doubt in mind, but I am not convinced by the above post. Also another thing, I've never heard of something called a Factory Class do you mean to say factory method instead or rather a static factory method then this blog
has a good explanation I got recently.
Also I bear a doubt in my mind,
How to write a singleton class.
Thanks in advance.
Please view this thread on topic to have more details.
PS. It is a good practice to check FAQ's of the forum and search the forum using the Search button on top to check if your question had been already answered. Please take time to the same before posting.
Of course, there are some issues regarding distributed systems or concurrence.
I may also have a scheduler class. this is the thing that says "on this day, this car will be used by this person". if i had two instances of that, they might both fight for the same resource. instead, i design my code so that everybody gets a reference to the same instance. everyone is talking to the SAME scheduler.
a factory class is a class who's job is to create instances of other classes. to corrupt the HFJ example, i may have a PizzaFactory class. you pass its method a parameter, and it returns a PepperoniPizza, a SausagePizza, or a CheesePizza.
Originally posted by Peter Chase:
Er, there's some rather vital "static" keywords missing from that "canonical" implementation of singleton.
That, plus the fact that the "canonical" example of a Singleton usually employs lazy instantiation to create the single instance, but that's splitting hairs really
Originally posted by R Lopes:
Sorry, my mistake
You're not the only one.
Log4J has the exact same problem with their NullAppender. There is a method called getInstance() with the following comment:
Whenever you can, use this method to retreive an instance instead of instantiating a new one with new.
Slight problem: that method is NOT static
So, in order to call a method to prevent creating a new object, you have to create an object first. Nice try guys
Originally posted by jignesh soni:
If you create a class with private constructor, how do you instantiate that class, if its not an inner class ?
As Rob Prime said, you instantiate the object inside the class, at this point
So, outside your class, you use getInstance method to get a reference to this object, i.e,
So, just to remeber,
"Private constructors prevent a class from being explicitly instantiated by callers"
[ April 08, 2008: Message edited by: neilson ramalho ]