Reputation: 965
I have been going through this tutorial and from what I understand, a singleton class can only be initialized once. Therefore I wrote the following 1 line of code:
public synchronized static DefaultHttpClient getThreadSafeClient {
**System.out.println("this should only happen once!!");**
I then wrote the following lines of code in my MainActivity's button:
HttpClient httpclient = multithreaded_httpclient.getThreadSafeClient();
HttpClient httpclient1 = multithreaded_httpclient.getThreadSafeClient();
I then pressed the button many times and to my surprise i found this in my logcat:
this should only happen once this should only happen once this should only happen once this should only happen once
I thought singleton classe's method only executes once... how is this possible ?
Upvotes: 0
Views: 169
Reputation: 10947
In a nutshell, the Singletons pattern means that:
new YourClass()
So, when any other class needs an instance of that class, they are enforced to call that factory method, since the constructor is private, and inside of that method, you write the code to ensure there is only one instance.
Thats all. With this only one object can be created, so all the possible instances of the object are actually the same, but of course any call to any public method of that object will be normally executed, no matter how many times it is called.
Upvotes: 1
Reputation: 12919
It seems there is a small misunderstanding related to Singletons
.
Singletons can only be initialized once, meaning there can only be one instance of it. Of course, the static method will be executed each time you call it, but the returned instance will always be the very same one.
Upvotes: 2