It is probably elementary but I have problem solving it.
I have a singleton and in every method call i send an object . the same one.so it looks like this :
mySingletone.getInstance.doSomethingXXX(MyObj)
mySingletone.getInstance.doSomethingYYY(MyObj)
Now, I want to stop sending it and put it inside the singletone.
I have a few optional solu开发者_如何学运维tions - 1. set it right after the first - getinstance call . very bad - cause I am not sure when will be the frst time. 2. I can erase the singletone implementation and send them to a public ctor - but then I will not be sure that it will be created once only.Is there a way to init a singletone only once?
Check out the Initialization On Demand Holder Idiom for the best way to implement a singleton pattern in Java.
http://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom
You can just set the value in your private constructor, which should be called only once.
If your Singleton class needs to doSomething with different MYObj then you should continue to do what you are doing.
If the Singleton should always use the same instance of MyObj (i think that's what you're asking for), you can create an instance of it in your Singleton (it would be better because it would be encapsulated/hidden from the client. (you can even encapsulate the MyObj class inside this class)
For example:
public class MySingleton {
private static MySingleton _instance = new MySingleton();
private MyObj _myObj = new MyObj();
private MySingleton() {
//set more stuff into _myObj if necessary
}
/*
//similarly you can replace the above 4 lines of code with this code:
private MyObj _myObj;
private MySingleton() {
_myObj = new MyObj();
//set more stuff into _myObj if necessary
}
*/
private static MySingleton getInstance() { return _instance; }
//other methods of the class use _myObj
// ...
//could even define MyObj class nested in this class
}
精彩评论