posted 22 years ago
yes..Adding to what Lasse had said, if you decide to make a class Singleton, you have better not have member variables declared for that class. If you do have member variables, be aware that there can be multiple threads accessing it at the same time.
Say if have a singleton class called Foo, and you have a newInstance() that looks like:
now it is possible that two threads can call newInstance() at the sametime!! so you can potentially have two instances instantiated and that's no good, its no longer a singleton then.
To prevent this, you must synchronize the method.
once synchronized, you can be assured that no two instances are ever created in that method.
Now if you DO decide to have member variables that allows write privileges, be sure to synchronize access to them. Usually this a pain because you will have to keep track everywhere in your application that can potentially access these member variables, so you will have to learn some defensive programming otherwise you can run into problems in running multi-threaded applications. However, if you design your objects as immutable, you can safely ignore this whole synchonizing, threading issues since you can't possibly write to these member instance variables, so there's no need to synchronize access to them.