Singleton Design Pattern Tutorial

[ad_1]
Get the Code:

Best Design Patterns Book :

Welcome to my Singleton Design Pattern Tutorial. The Singleton pattern is both easy to understand as well as useful. I’ll demonstrate first how to implement the Singleton pattern. Then I’ll provide and example of its usefulness with a Scrabble example.

Threads can sometimes play havoc with this pattern, so I’ll show you how to avoid those problems. I’ll also review how to use threads, LinkedLists and more.


Posted

in

by

Tags:

Comments

39 responses to “Singleton Design Pattern Tutorial”

  1. Md Farooq Avatar

    explanation is very neat and clean, Thank you Derek

  2. 2archarry Avatar

    The method getTiles should be synchronized to make it thread-safe .

  3. Thien Pham Quang Avatar

    why singleton become more complicated like that @@

  4. Hang Du Avatar

    In Singleton class getInstance method, why does the thread need to sleep for some time?

  5. Heiko Meyer Avatar

    The whole series on design patterns from you is awesome – thank you very much for your efforts on that!
    However in my opinion I think they would be twice as awesome if you would simply slow down – say about half the speed. No need to change anything else since the content is already great. Just give us 3 or 4 seconds every time you would otherwise flip to the next screen.
    For now I'm constantly doing play/pause and my mouse may quit service soon 😉

  6. Satish Goswami Avatar

    The second statement of printing the hash code at 10:38 should be :
    System.out.println("Instance 2 ID: " + System.identitiyHashCode(instanceTwo));

  7. Naveen Kumar Avatar

    best explained…… got the concept of Singleton… thanks

  8. Saurabh Agrawal Avatar

    for loop in getTiles should execute from i=0 to i<howManyTiles and not i<=howManyTiles
    In fact, we get 8 tiles every time we pass 7 in the argument.

  9. Archit Chhikara Avatar

    What is the advise you would give to a person who wants to learn more about Architectures? Any reference would be fine.

  10. Ameer ali khan Avatar

    purpose of singleton class is to create only one instance i think what derek is trying to show that thread can hamper this sole purpose of singleton class that is other thread can create other instance so in singleton class getInstance method should be synchronized.

  11. Sambit Kabi Avatar

    And yes just one thing to add , you can also use the Bill Pugh's singleton implementation which avoids the double checked locking and the synchronization is handled by the JVM itself.

  12. Sambit Kabi Avatar

    Great one..The intention of Singleton pattern is very well fulfilled.But one thing I would like to suggest is that in multi-threaded environment we need to make the instance variable volatile. Making it volatile will prevent the re-ordering of the instructions and thereby avoiding undesired behavior.

  13. Michael Gates Avatar

    Another way you could do this is by instantiating the Singleton instance in-line. You don't have to initialize it on a narrower scope.

  14. greg77389 Avatar

    Yes but what can you do with a singleton that you can't just do with a "static" class (a class that can't be instantiated at all and has all static members and functions)?

  15. Anmol Singh Avatar

    Awesome videos mate! Thanks a bunch! 🙂

  16. satish rao Avatar

    Hi, Doesn't this mean that there is no randomness in giving out scrabble letters, if you're looping through the letterList ? So, the first person should get all 'a's . Isn't this wrong!?

  17. Goran Belfinger Avatar

    Do not use double locking mechanism because you can't be sure if it will work on every JVM. Simply put: when you create a new instance and assign it to a variable, it is instantly created in memory but it can be assigned with a delay. It means that the second thread could still pass through the second if statement.
    Use inner class which will hold the singleton instance. Singleton will still be lazy loaded because the class is not loaded until it is requested:
    public class LazySingleton {
    private LazySingleton(){}

    public static LazySingleton getInstance(){
    return LazyLoader.INSTANCE;
    }

    private static class LazyLoader{
    private static LazySingleton INSTANCE = new LazySingleton();
    }
    }

  18. CobraL0rd Avatar

    Thanks a lot! You don't have Inversion of Control design pattern huh?

  19. stepho670 Avatar

    Can you be my professor? The world needs more people like you!

  20. Teofilo Francisco Avatar

    Thanks for so easily explanation

  21. Abhinay Sama Avatar

    In non-static methods like "getTiles", why did you use the object name to access a non-static variable?
    firstInstance.letterList
    Which is as good as just this.letterList since you're already in the object context.

  22. Sandhya Sharma Avatar

    superb way of explaining….about all the program line by line!!!
    Really sometimes its hard to understand why something is done in certain way ad evething is use in some purpose!!

  23. Tamanna Lekhwani Avatar

    I don't understand why do we need a Singleton class here. What would have gone wrong if we would have simply made the letterList static ? Can anyone please care to explain ?

  24. Arika Saputro Avatar

    I think you are wrong in writing instance2 hashcode and playertwotile, it make me confused

  25. Bilal Sammour Avatar

    Great lessons thank you.
    What is the difference between ArrayList and LinkedList?

  26. redsnakeintown Avatar

    Well you should have printed the hashcode of instanceTwo..you tried to print both places the same "newInstance"

  27. Khosi Lwazi Avatar

    lol "mass disaster"

  28. vishal verma Avatar

    Hey Derek, I had one question though, what was the purpose of Boolean variable firstThread here?

  29. bigmohen Avatar

    Great tutorial, thank you so much.
    my question is what is the difference between this singleton pattern to yours

    public class Singleton {
    private static Singleton ourInstance = new Singleton();
    public static Singleton getInstance() {
    return ourInstance;
    }
    private Singleton() {
    }
    }
    this is the default IntelliJ pattern, in your example you've check if it's null, is there any difference performance wise ? or any thing worth to mention ?

  30. Arka Prava Ghosh Avatar

    What if I make a clone of the singleton object ?

  31. Przemysław Woźniak Avatar

    I'd like to ask question regarding synchronized block: does "Singleton.class" mean the same as "this"?

  32. xiyu xie Avatar

    Hi Derek, thank you so much for such an excellent explanation. Could explain in more detail why the second Synchronized method on Singleton.class is preferable?

  33. 15bigdave Avatar

    I'm on mobile so I'm not sure if anyone has said anything. in your get tiles loop, it should be strictly less than instead of less than or equal to number of tiles. right now you're returning 8 tiles for getTiles(7).

  34. Jack Bauer Avatar

    Good tutorial but one thing is wrong. The getInstance Method should be synchronized. Because a thread could lose CPU time at the if!

  35. Miguel Adrian Domingo Avatar

    Hey man! Nice tutorials, yet I can't help but be curious: are you using mechanical keyboard? If so, what model? 🙂 I reckon its a blue switch

  36. Antoni Szewczyk Avatar

    Hello Derek! Thanks for you tutorial again! What are the advantages and disadvantages of employing lazy instantiation? When should I use it and when it is not a good idea?

  37. gujaalsmanda Avatar

    great tutorial Derek i finally understood what each line does.

  38. Alen Mikic Avatar

    Great tutorial as always. It would be great if you made a tutorial on Spring mvc 4 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *