user3134565
user3134565

Reputation: 965

singleton class doesn't work

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

Answers (2)

Carlos Robles
Carlos Robles

Reputation: 10947

In a nutshell, the Singletons pattern means that:

  • The constructor of your class is private
  • You create a public factory method, where YOU take care of:
    • If it is the first time that an instance is requested, create an instance with new YourClass()
    • If an instance was already created in a previous call, you don't create a new one, but return the previous one.

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

FD_
FD_

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

Related Questions