[java] Singleton pattern

Started by
4 comments, last by moth_wannaKnow 17 years, 7 months ago
Hallo! I am programming in java and I have to make sure that only one instance of a class is created. This instance should also be used by other classes. I am trying to use singleton but, it is not working.... This is how i want to get hold of my con: con c = new con.getTheOne_con(); but it's not correct because when I compile it I get that it can't be resolved to a type In my con class: private static con one_con = null; private con() { counter = counter +1; System.out.println("con created: "+ counter); } public static synchronized con getTheOne_con() { if(one_con == null) { one_con = new con(); } return one_con; } please help.....
Advertisement
Quote:Original post by moth_wannaKnow
Hallo!

I am programming in java and I have to make sure that only one instance of a class is created. This instance should also be used by other classes. I am trying to use singleton but, it is not working....

This is how i want to get hold of my con:
con c = new con.getTheOne_con();

Hint, think about what the emphisized line is TRYING to do...

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.

if it exist it should return it and if it does not it should be created... what am I missing?
What does new do? What type of an argument does it take?

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.

I'd say your problem is that "new", you're trying to new a return value which isn't exactly what new is for so that's why it's not working (you can only new types) - and really counterintiutive when you're using Singletons (only one instance is allowed yet you're trying to make a new one?).

So, just remove the new:
con c = con.getTheOne_con();
[ ThumbView: Adds thumbnail support for DDS, PCX, TGA and 16 other imagetypes for Windows XP Explorer. ] [ Chocolate peanuts: Brazilian recipe for home made chocolate covered peanuts. Pure coding pleasure. ]
Thanks

It's a little bit to late for me I can't think that clear 3- 4 oclock in the morning...but removed "new" and ofcause it's working now thanks again...

Nu ska jag sova!

This topic is closed to new replies.

Advertisement