Results 1 to 14 of 14
Like Tree3Likes
  • 2 Post By gimbal2
  • 1 Post By SurfMan

Thread: Doubt in Singleton Pattern

  1. #1
    Join Date
    Aug 2013
    Posts
    55
    Rep Power
    0

    Default Doubt in Singleton Pattern

    In singleton pattern just having a static field is not enough? Do we really need to have a private constructor?

    I can have a static field and have a public constructor and still say it is singleton.

  2. #2
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    946
    Rep Power
    2

    Default Re: Doubt in Singleton Pattern

    You expect a Singleton to have one and only one instance in the JVM. That's where the name comes from: SINGLEton. If you add a public constructor, you can manually create another instance so more than one instance exist. In the end you will run into problems, especially when you're working in a team or creating a public API.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  3. #3
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,002
    Rep Power
    6

    Default Re: Doubt in Singleton Pattern

    When you have to choose between proper code design and doing less effort, please choose for proper code design.
    kneitzel and SurfMan like this.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  4. #4
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    946
    Rep Power
    2

    Default Re: Doubt in Singleton Pattern

    Quote Originally Posted by gimbal2 View Post
    When you have to choose between proper code design and doing less effort, please choose for proper code design.
    ... which in the end will save you time and thus less effort, because you don't spend three days debugging why your singleton does or does not contain a specific value you expected there.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  5. #5
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,002
    Rep Power
    6

    Default Re: Doubt in Singleton Pattern

    Long term thinking - it is one of those things that separates the engineers from the programmers :)
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  6. #6
    Join Date
    Aug 2013
    Posts
    55
    Rep Power
    0

    Default Re: Doubt in Singleton Pattern

    Well I am just trying to think differently. Just look at the example below:

    SingleObject.java
    Java Code:
    public class SingleObject {
    
       //create an object of SingleObject
        static SingleObject instance = new SingleObject();
    
       //make the constructor private so that this class cannot be
       //instantiated
       public SingleObject(){
    	   getInstance();
       }
    
       //Get the only object available
       public static SingleObject getInstance(){
    		System.out.println("instance:"+instance);
    		return instance;
       }
    
       public void showMessage(){
          System.out.println("Hello World!");
       }
       
    }
    SingletonPatternDemo.java
    Java Code:
    public class SingletonPatternDemo {
       public static void main(String[] args) {
    
          SingleObject object1 = new SingleObject();
    
          
          SingleObject object2 = new SingleObject();
          
          if((object1!=null)&&(object2!=null))
          {
              if(object1.equals(object2))
              {
            	  System.out.println("Equal");
              }
              else
              {
            	  System.out.println("Not Equal");
              }
          }
    
       }
    }
    Your comments are appreciated.

  7. #7
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    946
    Rep Power
    2

    Default Re: Doubt in Singleton Pattern

    How does your Demo test the SingleObject? Showing a message from a Singleton is not a good test case.

    - Your constructor doesn't do anything. The return value of getInstance() is ignored. You don't have a choice there, since the constructor doens't even have a return value.
    Java Code:
    public SingleObject(){
           getInstance();
       }
    - Testing for != null when you created a new object the line above that, is pretty useless.
    - Testing with equals() without overriding hashcode() and equals() in SingleObject is useless too. (override - Overriding equals and hashCode in Java - Stack Overflow)


    Look at the next case, modelled after your example:
    Java Code:
    import java.util.ArrayList;
    import java.util.List;
    
    public class SingletonBroken {
        private static SingletonBroken instance = new SingletonBroken();
        private List<Integer> numbers;
    
        public SingletonBroken() {
            numbers = new ArrayList<Integer>();
        }
    
        public static SingletonBroken getInstance() {
            return instance;
        }
    
        public void addNumber(int i) {
            if (numbers.contains(i)) {
                throw new IllegalArgumentException("Number already exists");
            }
            else {
                numbers.add(i);
            }
    
        }
    
    }
    
    
    public class SingleBrokenTest {
    
        public static void main(String[] args) {
            SingletonBroken object1 = new SingletonBroken();
            SingletonBroken object2 = new SingletonBroken();
    
            object1.addNumber(1);
            object2.addNumber(1);
    
    
            SingletonBroken object3 = SingletonBroken.getInstance();
            SingletonBroken object4 = new SingletonBroken();
    
            object3.addNumber(1);
            object4.addNumber(1);
    
            SingletonBroken object5 = SingletonBroken.getInstance();
            SingletonBroken object6 = SingletonBroken.getInstance();
    
            object5.addNumber(1);
            object6.addNumber(1);
        }
    }
    If you run this, you will see that only object6 throws the expected IllegalArgumentException. All the other objects are NOT singletons. They are NOT the same instance and do not contain the same data.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  8. #8
    Join Date
    Aug 2013
    Posts
    55
    Rep Power
    0

    Default Re: Doubt in Singleton Pattern

    You are further confusing me. Someone else please help me understand what is wrong or right with my example.

  9. #9
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    946
    Rep Power
    2

    Default Re: Doubt in Singleton Pattern

    You're welcome.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  10. #10
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,002
    Rep Power
    6

    Default Re: Doubt in Singleton Pattern

    Quote Originally Posted by suhaas_mohandos View Post
    You are further confusing me. Someone else please help me understand what is wrong or right with my example.
    I can't make your brain work better.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  11. #11
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    946
    Rep Power
    2

    Default Re: Doubt in Singleton Pattern

    Quote Originally Posted by suhaas_mohandos View Post
    You are further confusing me. Someone else please help me understand what is wrong or right with my example.
    If you don't understand my answer, then ask a question about my answer. Don't ignore answers because you don't understand them.

    In short, your "Singleton" is not a Singleton since multiple instances can exist in the JVM.
    gimbal2 likes this.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  12. #12
    Join Date
    Aug 2013
    Posts
    55
    Rep Power
    0

    Default Re: Doubt in Singleton Pattern

    If you don't understand my answer, then ask a question about my answer. Don't ignore answers because you don't understand them.

    In short, your "Singleton" is not a Singleton since multiple instances can exist in the JVM.


    Ok. Forget about the equals and hashcode for the moment because I am just using equals method to compare if the two objects are same. The below line of code prints the output

    instance:SingleObject@17dfafd1
    instance:SingleObject@17dfafd1

    SingleObject.java
    Java Code:
    System.out.println("instance:"+instance);
    which is nothing but the same. But when I use the equals method in SingletonPatternDemo.java it prints "Not equal". How?

  13. #13
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    946
    Rep Power
    2

    Default Re: Doubt in Singleton Pattern

    The message "instance:SingleObject@17dfafd1" is printed from the static instance field because you call the getInstance() method. The SingleObject that you print is the static field. Like I said, the constructor just calls the method, but it does not use or replace the instance you are looking for. The two objects you create later are separate instances. In total you now have THREE instances of SingleObject:
    Java Code:
        public static void main(String[] args) {
    
            SingleObject object1 = new SingleObject();
            SingleObject object2 = new SingleObject();
            
            System.out.println("instance:"+object1);
            System.out.println("instance:"+object2);
    ...
       }
    prints:

    instance:com.qprcostcontrol.plugin.SingleObject@3a 3ee284
    instance:com.qprcostcontrol.plugin.SingleObject@3a3ee284
    instance:com.qprcostcontrol.plugin.SingleObject@768965fb
    instance:com.qprcostcontrol.plugin.SingleObject@36867e89
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  14. #14
    kneitzel is offline Senior Member
    Join Date
    Feb 2014
    Posts
    447
    Rep Power
    1

    Default Re: Doubt in Singleton Pattern

    Hi,

    just print the 2 instances you create inside main. Maybe that helps you to understand.

    You created 3 instances of your SingleObject class:
    - 2 instances are created inside your main
    - 1 instance is generated with the static reference inside these objects.

    So you just print the last one. But that does not change anything about the fact that you created 3 instances of your code. And this simply leads to problems when you extend your singleton class!

    Just imagine, you add something to it. Just add a
    public int someNumber;

    In a real singleton, only one instance will be available so there is no risk. There will only be one number.

    But in your example? You could use object1, object2 or the getInstance result.

    So just make the constructor private and the getInstance static and this problem cannot occur any longer.

    Hopefully you understood the Singleton pattern now.

    With kind regards,

    Konrad

Similar Threads

  1. Please help with Singleton pattern.
    By fatabass in forum New To Java
    Replies: 19
    Last Post: 03-10-2012, 07:00 PM
  2. Singleton Pattern
    By ShaileshRaj in forum Advanced Java
    Replies: 5
    Last Post: 02-29-2012, 04:52 PM
  3. singleton design pattern
    By ziaur25@gmail.com in forum Advanced Java
    Replies: 2
    Last Post: 02-25-2011, 08:28 PM
  4. Singleton Pattern
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 01-24-2008, 03:21 PM
  5. singleton pattern
    By Peter in forum Advanced Java
    Replies: 1
    Last Post: 07-09-2007, 04:45 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •