This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I dont understand what is singleton object. I looked online and it says that singleton class is a class that can have only one object at a time. What does this mean ? I dont think it means we can only creatte one object of a class. Can anyone pls explain preferably with example. Please also explain Factory class too. Thanks
Hi, 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.
There had been a discussion on same a few days ago in this same forum. 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.
Look the following code. It's the canonical implementation of a Singleton. The private constructor avoids other classes to instantiate Singleton objects. The only way to get a Singleton instance is calling the method getInstance(), that will always return the same instance. Of course, there are some issues regarding distributed systems or concurrence.
in brief... a singleton means you can only create the object one time within your program. say i had a car rental program. one of my classes would be a Car. clearly, i'd want to create many, many instances of cars, assuming i have more than one to rent.
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.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Joined: Feb 29, 2008
Originally posted by Peter Chase: Er, there's some rather vital "static" keywords missing from that "canonical" implementation of singleton.