Singleton Design Pattern Tutorial

24
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.

Nguồn:https://wijstaanvooronzegrondrechten.org/

24 COMMENTS

  1. I have to say, first of all, your tutorials are great, in this particular one there was only one section that had some issues and wasn't reflecting what you were stating during that part of the video (even though your statement was right, just not for that code).
    Around 11:00 the lines 21-27 for ScrabbleTest.java should be modified to:

    System.out.println("Instance 2 ID: " + System.identityHashCode(instanceTwo));

    System.out.println(instanceTwo.getLetterList());

    LikedList<String> playerTwoTiles = instanceTwo.getTiles(7);

    System.out.println("Player 2: " + playerTwoTiles);

  2. It is kind of disappointing that Java Enums have been around since Java 5 (circa 2005), but this video shows Singleton in Java 1.4.2 style. At the very least, I would've shown the simplicity of Java Singleton using enums at the very end to appreciate the power of this approach.

  3. everybody mentions the double instance 1 hashcodes, but no mention of playerOneTiles being printed twice instead of playerTwoTiles. great tut, but after 3 years, annotations could have come in handy!

  4. Aren't you supposed to add the volatile primitive to the firstInstance field? I heard that all of the synchronization will be pointless if the field itself isn't. Here's a link that explains why. https://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html

  5. Why is it so important to slow down first thread? doesn't synchronized(Singleton.class) statement make sure that only one thread will be executed at a time? i have deleted whole "slow down" section from your code and it still worked perfectly.

  6. Singleton Pattern: "It is used when you want to eliminate the option of instantiating more than one object." Once again you answered something so simply that 3 other blog posts and 2 videos didn't convey. Maybe I just wasn't paying attention, but you seriously have a way of explaining things in a way that makes sense the first time. Awesome. And thank you!

LEAVE A REPLY

Please enter your comment!
Please enter your name here