I want to implement singleton for httpconnection.... I have a servlet as a server and client side I use android. I have to use the connection man开发者_如何转开发y times. Currently, each time I am doing a new connection, but that is not the right way.. So I want to implement singleton for the httpconnection so I can use that instance in each android class..... so help me.. what type of code i write..
Show some code from what you have, and I can help you more...
Off the cuff, I would say make the httpconnection object a member variable of the class, and any time you're making a new one, reference the member variable instead.
While binding a singleton with a live HTTPUrlConnection
instance is good from a reusable practice, but you should also consider how often a call will be made to the server. If your Android application[s] make a lot of connections and need fast response, then there's no point creating a chokehold on such a resource. But if that's not the case, you can simply have an instance variable, and initialise it within the constructor of your particular class. Something like -
public SomeClass {
HTTTPUrlConnection conn = new HTTPUrlConnection(...);
SomeClass instance = new SomeClass();
private SomeClass() {}
public static getInstance() {
return instance;
}
}
Some might contend why initialise the instances inline and not within the getInstance
method, but i believe this is best in terms of thread safety. Just Google on Singletons are not good from thread-safety perspective.
精彩评论