Singleton Pattern - Design Patterns (ep 6)

Sdílet
Vložit
  • čas přidán 26. 06. 2024
  • Video series on Design Patterns for Object Oriented Languages. This time we look at the Singleton Pattern.
    ► The playlist
    • Design Patterns in Obj...
    ► Head First: Design Patterns
    geni.us/nlbA6
    ► Design Patterns: Elements of Reusable Object-Oriented Software
    geni.us/PsXmo
    ► Clean Code Talks at Google, by Miško Hevery
    • "The Clean Code Talks ...
    • "The Clean Code Talks ...
    • The Clean Code Talks -...
    • The Clean Code Talks -...
    • How to Write Clean, Te...
    💪 Patreon Community
    / christopherokhravi
    📚 Products I Recommend
    geni.us/71ZXF

Komentáře • 491

  • @mphophantshang9087
    @mphophantshang9087 Před 5 lety +398

    Boss: My wife is cheating on me
    Programmer: One man's constant is another man's variable....

  • @vineetherenj3143
    @vineetherenj3143 Před 3 lety +88

    Me: Let me learn about Singleton pattern.
    Christopher: never use singleton pattern.
    Me: -_-

    • @eugeneganshin2934
      @eugeneganshin2934 Před 3 lety +1

      You can use it tho. In Typescript Nestjs Framework alsmost every class is a singleton and its fine.

    • @PeterFlemmingNielsen
      @PeterFlemmingNielsen Před 2 lety

      You should never use it, except when you should. (eg. it is good to prevent database connection leaks)

    • @AlonGvili
      @AlonGvili Před 2 lety

      @@eugeneganshin2934 so like redux store is a singleton in a javascript/react world ?

  • @mohammadnaseri5045
    @mohammadnaseri5045 Před 7 lety +183

    One of the best series I have ever watched. Keep going on dude!

    • @ChristopherOkhravi
      @ChristopherOkhravi  Před 7 lety +8

      mohammad naseri thank you for the kind words. I'm glad it's useful :)

  • @CognitiveSurge
    @CognitiveSurge Před 7 lety +40

    Love these videos, thanks Christopher! The Head First series is great.

    • @ChristopherOkhravi
      @ChristopherOkhravi  Před 7 lety +1

      Karl Hadwen thanks! I'm very glad they're useful. Thanks for watching :)

  • @Tapuck
    @Tapuck Před 6 lety +12

    Your editing is absolutely fantastic. The stream of knowledge never stops or slows down.

  • @lyusienlozanov1632
    @lyusienlozanov1632 Před 6 lety +3

    Everything makes sense with that kind of explanation! Thanks, Chris!

    • @ChristopherOkhravi
      @ChristopherOkhravi  Před 6 lety +1

      Thank you for the very kind words. Much appreciated and I'm glad to hear it. Thanks for watching :)

  • @ckmedia6120
    @ckmedia6120 Před 5 lety +3

    This is why I love the internet, good videos with good info. My man!

  • @hoelefouk
    @hoelefouk Před 4 lety +5

    If there is anything comparable to your teaching skills, it's your skills to have amazing intros. Intro for this particular video is simply genius. Your intros are so underrated man!

  • @aniketb2010
    @aniketb2010 Před 5 lety +9

    “One man’s constant is another man’s variable”... Woow!!

  • @mikhailbisserov8017
    @mikhailbisserov8017 Před 6 lety +54

    That's a good video. Especially the code smell part. I would add though that to ensure single instance you also need to wrap instance creation with lock (Monitor), because nowadays threads are used left and right. In fact, "double-checked locking" (that's a pattern) should be used
    if (instance == null) {
    lock (_lockObject) {
    if (instance == null) {
    instance = new Singleton();
    }
    }
    }

    • @GohersWay
      @GohersWay Před 3 lety

      Sorry for asking such a newb question but what is purpose of locking here.

    • @mikhailbisserov8017
      @mikhailbisserov8017 Před 3 lety +12

      @@GohersWay Locking prevents execution of the enclosed code by multiple threads. We want "instance = new Singleton()" execute only ONCE in entire process lifetime and for that we need to make sure that inner "if (instance == null)" is never evaluated SIMULTANEOUSLY (but theoretically it can happen more than once, if two threads happen to access the singleton instance for the FIRST time simultaneously). Now, why do we need outer "if (instance == null)" - because it's much cheaper than lock in terms of CPU. If a web application runs for 30 minutes before process recycling, then 99.9% of instance access cases by different threads will go no further than outer if, 0.09% will create monitor, wait on that monitor, and evaluate inner if, and 0.01% will actually execute inner if's enclosed code (instance = new Singleton).

    • @good_life_videos
      @good_life_videos Před 2 lety

      @@mikhailbisserov8017 but even if two threads access that part of creating the object, why should it be a concern ? considering, first instantiation call is just necessary (but state will always be random, so hardly matters who creates it finally or been changed by some other threds at same time)

    • @mikhailbisserov8017
      @mikhailbisserov8017 Před 2 lety +3

      @@good_life_videos if two threads create instances of the object, it's not Singleton by definition. WHY we want to create it only once is an out-of-scope question. It's a given task, purpose of Singeton. Usually it's for performance and memory conservation, maybe even acquiring lock to some unique underlying resource, but again, it's out of scope.

  • @sibinM11
    @sibinM11 Před 3 lety

    this guy and explanation is pure gem

  • @sammclaren6965
    @sammclaren6965 Před 10 měsíci

    That's what I call 'in-depth explanation'! Awesome work.

  • @IamCagedAnimal
    @IamCagedAnimal Před 6 lety +15

    U, my good Sir are born for teaching, really nice and simple explanation for everyone to understand. Keep up the good job!
    cheers

  • @ruvishkarathnayake9125
    @ruvishkarathnayake9125 Před 4 lety +2

    The way you teach these lessons is perfect. This is a good example for my lecturers how to teach these stuff.

  • @jvsnyc
    @jvsnyc Před 2 lety

    The Clean Code links are all great! Now, back to your videos! I wound up learning as much from this as any of your others in this playlist, thanks to the excellent links provided in the description. Singletons seem very convenient, until test-time...

  • @luli829
    @luli829 Před 6 lety

    Already learned this in university and now planning to review again, my professor who teaches that course is very good, and your lecture is as good as the course I learned before ! Thank you so much ! Waiting for more

  • @karzo222
    @karzo222 Před 3 lety +1

    You are criminally underrated. Deserves more followers. Top notch.

  • @ariaien8637
    @ariaien8637 Před 4 lety

    Singleton design pattern is simple, however, complicated! every line of the code was explained thoroughly and beautifully.. well done! One of the best videos ever for Singleton!

  • @prapulkrishna
    @prapulkrishna Před 4 lety

    You are one of the best teachers on the planet. Thanks for the videos.

  • @SaurabhGuptaicecool
    @SaurabhGuptaicecool Před 4 lety +2

    This series is greatest I've ever encountered on youtube on any topic, period.

  • @kirubababu7127
    @kirubababu7127 Před 3 lety +1

    The way you teach is fantastic, you are my inspiration.

  • @uzil24
    @uzil24 Před 5 lety +1

    Thank you for this video and all the rest. I really hope to find every single Design pattern explained by you in this play list.

  • @sushantkumar1845
    @sushantkumar1845 Před 3 lety

    The best playlist (on IT/Sw) I have ever watched on CZcams

  • @user-sh9bj8qz3j
    @user-sh9bj8qz3j Před 5 měsíci

    A clear video on single ton design pattern. Thank you.

  • @vyaasshenoy1884
    @vyaasshenoy1884 Před 5 lety +1

    Your explanation is clear and precise. I enjoyed the video and was able to understand the nuances of this pattern very well.

  • @liveyounganastasia
    @liveyounganastasia Před rokem

    I love how you explained this. Very clear. 👏

  • @DAS-jk3mw
    @DAS-jk3mw Před rokem

    This is the best explanation of a Singleton pattern ever !!

  • @jaycelila6258
    @jaycelila6258 Před 7 lety

    don't understand why this video is not popular than it has to be. You are amazingly well explaining abstract concepts so dumb like me can understand. Thanks.

  • @dalitsobotha7932
    @dalitsobotha7932 Před 3 lety +1

    I love the way you teach. Your explanations are thorough and the way you speak is very captivating. Straight to the point, you are not a time waster.

  • @ZenMonkIlya
    @ZenMonkIlya Před 4 lety

    Very informative! Thank you very much for this fantastic explanation, and for presenting it in such a good-natured way!

  • @seguncodes3136
    @seguncodes3136 Před 3 lety

    The best explanation of Singleton pattern i have come across

  • @pervanadurdyyeva1920
    @pervanadurdyyeva1920 Před 3 lety

    Simplest and clear explanation I've come across. Thanks

  • @abedalrawas2656
    @abedalrawas2656 Před 7 lety

    These videos are so precious thank you!

  • @rustemduran4248
    @rustemduran4248 Před 2 lety

    NIce man, totally grasped for the first time, thank you so much.

  • @user-qg8ku9gv1l
    @user-qg8ku9gv1l Před 3 lety

    Super clear! Thanks Christopher!

  • @DominikRoszkowski
    @DominikRoszkowski Před 7 lety +10

    Thanks, your explanation was clear and convincing :)

  • @exoticcoder5365
    @exoticcoder5365 Před 3 lety +1

    Gooooooooood one !!!! Very clear ! Clear all my concepts !

  • @johnyjohnjohny8014
    @johnyjohnjohny8014 Před 7 lety +2

    This is quality man. Keep the good work, youtube definitly needs that. Well done

  • @clementtytube
    @clementtytube Před 2 lety +1

    First time seeing your videos... I give a 10000 likes for your cuts and edits. Your videos are full of info (no lags and time waste). That itself proves you value your trade.. Kudos

  • @priyankmungra29
    @priyankmungra29 Před 3 lety +1

    Thank you for making this series ❤❤❤

  • @lindawisebear
    @lindawisebear Před 3 lety

    It was really helpful that you went through the code in this video; great series! :)

  • @thomas2957
    @thomas2957 Před 5 lety

    You're views must really go up every December/January. Exams time and your explanations are great, thanks man

  • @oussamaml4161
    @oussamaml4161 Před 6 lety

    i got a UML exam tomorrow , and i've been watching your video , your videos are saving my life right now

  • @gavinmcgregor3219
    @gavinmcgregor3219 Před 7 lety +4

    Just wanted to let you know that you are amazing for making this series!

  • @IntelliAbb
    @IntelliAbb Před 7 lety

    As much as we try to avoid Singletons, we do run into scenarios where we have to use one. Specially when working with native Android using Java where for creating Fragments, we use a public Instance property to get access to it. These Instances are then held in memory for various operations done by the OS.
    Great series, keep it up :)

  • @Metachief_X
    @Metachief_X Před 4 lety

    god bless you, christopher. Please keep making videos!!

  • @monjasonsteng7861
    @monjasonsteng7861 Před 3 měsíci

    This is perfect. Thank you so much.

  • @Death8ball
    @Death8ball Před 7 lety +1

    Fantastic series. When I get my first dev job I will do what I can to support you.

  • @MrTrik15
    @MrTrik15 Před 5 lety

    Clear, audible video. Keep it up

  • @zolisawelani9338
    @zolisawelani9338 Před 3 lety

    Super awesome mate. Clear explanation.

  • @glenndify1
    @glenndify1 Před 7 lety +2

    you have really simplified design patterns ... classic explaination ... thank you very much

    • @ChristopherOkhravi
      @ChristopherOkhravi  Před 7 lety

      +Glenn Dsilva Thanks for letting me know! :) And thanks for watching!

  • @edudestroer
    @edudestroer Před 2 měsíci

    Thank's for all the Knowledge🤜

  • @rusiraliyanage6643
    @rusiraliyanage6643 Před 3 lety

    Hey SIr , I am Sri Lankan IT Undergraduate , you do explain these design patterns very well and Thank You So much. It was really helpful me to figure out the answers for the design patterns questions in our university :)

  • @sumitkapadia1509
    @sumitkapadia1509 Před 6 lety +5

    The way you jump entered, I expect to hear "Hey Vsauce" :P . Awesome video.

  • @sarahlee6976
    @sarahlee6976 Před rokem

    BEST VIDEO EVER!!!!! So much better than university lectures

  • @pw.70
    @pw.70 Před rokem

    Brilliant work - thank-you.

  • @AVBFANS
    @AVBFANS Před 6 lety +1

    great video. finally I found explanation in a style that I can understand clearly. Thanks for the lesson. I am now a subscriber.

    • @ChristopherOkhravi
      @ChristopherOkhravi  Před 6 lety +1

      +AVBFANS Awesome! Welcome to the channel :) And thank you for sharing your thoughts :)

  • @user-gb7cp5vz4q
    @user-gb7cp5vz4q Před 5 lety

    Thanks a lot! Very cool vivid explanations and examples! Thanks! Thanks! Thanks!

  • @naffiahanger9316
    @naffiahanger9316 Před 2 lety

    Your explanation of concepts are easy to understand 👏👏👏👏👏

  • @gg4eva763
    @gg4eva763 Před 2 lety

    Oh my god, you are a good explainer! I'm actually understanding what's happening

  • @mhshbht12
    @mhshbht12 Před 7 lety

    very good explanation of Singleton. Thanks Christopher

  • @SantanPereira
    @SantanPereira Před 7 lety

    I have watched all your videos on Design Pattern, You rock!!! keep up the good work. :)

  • @Wwise_sounds
    @Wwise_sounds Před rokem

    SNHU is using this video as material reference. you should feel proud that an university is using your videos to teach new students :)

  • @VaibhavJain
    @VaibhavJain Před 4 lety

    Liked the way you describe different aspects of decision making and assumptions related to pattern

  • @Mari99Hamida
    @Mari99Hamida Před rokem

    Clearly explained ! thank you .

  • @webb-developer
    @webb-developer Před 11 měsíci

    this amazingly amazing , thankyou brother.

  • @user-xs4gu6jd8m
    @user-xs4gu6jd8m Před 11 měsíci

    That was great! thank you 🙌

  • @christianmelot3201
    @christianmelot3201 Před 3 lety

    Thank you for your videos !

  • @JohnDoe-ej6vm
    @JohnDoe-ej6vm Před 3 lety

    such a wonderful lecture . concept clear now.

  • @always90s
    @always90s Před 7 lety +3

    Thanks Christopher! I will definitely check out those links. On to the next pattern :)

    • @ChristopherOkhravi
      @ChristopherOkhravi  Před 7 lety

      Hitesh Rana cool! They're worth the time. Misko seems like a very smart guy. Thanks for watching!

  • @rahulkmail
    @rahulkmail Před 3 lety

    Explained the matter nicely.

  • @kasunperera9700
    @kasunperera9700 Před 5 lety

    thanks chrostoper the best video about singleton i ever watched

  • @mayankgupta4243
    @mayankgupta4243 Před 7 lety

    Thanks Christopher really your explanation is very good

  • @rajeshrathod9329
    @rajeshrathod9329 Před 7 lety

    Very nice and detailed explanation of design pattern concepts.... I am waiting for other remaining design patterns videos ..... Thank you very much.

  • @timothyjohns8775
    @timothyjohns8775 Před 6 lety +9

    Not sure about other languages, but in C++, the preferred approach to singletons is known as the Meyers Singleton (named after Scott Meyers who included it in his book Effective C++). The idea is to declare the variable within a method rather than as a member variable. This is thread safe, and it also allows you to skip the check to see whether or not the singleton exists. The code looks like this:
    class Singleton {
    private:
    Singleton() {}
    public:
    static Singleton& getInstance() {
    static Singleton instance;
    return instance;
    }
    };

    • @yoavmor9002
      @yoavmor9002 Před rokem +1

      I don't think intra-method static variable magic exists in non C languages, I think it's mostly a C thing. By the way, I'm assuming you meant static Singleton instance = new Singleton()

    • @Remist0
      @Remist0 Před rokem +1

      @@yoavmor9002 It's not a pointer, so they did not mean that.

  • @LavGupta08
    @LavGupta08 Před 7 lety +1

    thanks again Christopher. your videos are great

  • @AngelFormica
    @AngelFormica Před 6 lety

    Excellent. easy to understand. Thank you.

  • @mehakjain5384
    @mehakjain5384 Před 6 lety +6

    One of the best video series I have ever seen. Superb explanation. Quite like the way you do these videos in your own style. Keep up the good work.
    P.s. loved ur writing and honesty :P

    • @ChristopherOkhravi
      @ChristopherOkhravi  Před 6 lety +2

      Thanks! I'm glad to hear that the style works :) Thank you for the encouragement and for watching the series :)

  • @tivmego
    @tivmego Před 7 lety +5

    watching keenly!

  • @egruper
    @egruper Před 6 lety +1

    had to add - you are amazing! great vids once again Thank you.

  • @kevinbenavides92
    @kevinbenavides92 Před 6 lety

    You are a great instructor. Keep it up please.

  • @irshuck
    @irshuck Před 6 lety +2

    Woooow, Thanks christopher for this wonderful series. Your teaching style is awesome. waiting for other design patterns :)

    • @ChristopherOkhravi
      @ChristopherOkhravi  Před 6 lety

      +Irshad ck Thank you. Makes me glad to hear. Next one is coming very soon. Thanks for watching :)

  • @Flutterdev6391
    @Flutterdev6391 Před 10 měsíci

    really awesome explanation

  • @ponnlaksmi2903
    @ponnlaksmi2903 Před 4 lety

    Explained well thanks buddy 😊

  • @betterculture
    @betterculture Před 6 lety +9

    Great video! However, the argument is not that Singletons are necessarily bad except that they are misunderstood, often abused and can introduce unwanted side effects when used without proper thought -- a lot of frameworks use Singletons :D.
    For instance, I have this piece of (framework) code that manages all of my configurations (and of subsystems) and the construction of this object is really heavy and doesn't even lend itself to a prototype or flyweight. It is important that these bits of configuration happen only once at application startup. Instead, I hide my singleton configuration instance behind an abstraction and delegate the construction and life cycle to a DI / IOC container. In other words, users only have to depend on that abstraction e.g. IConfigurationManager etc.
    In addition, the one thing (or two) I think you're missing is the issue of potential race conditions or thread-safety in concurrent systems when handling stuff like this manually -- why it's important to use a good DI framework and instead depend on abstractions. Plus, it is your responsibility to ensure that your object is IMMUTABLE upon construction and member access is read-only.

  • @kensearle4892
    @kensearle4892 Před 5 měsíci

    Thank you! Good points.
    The only time I have used a Singleton is when I was developing my own small website, wanted a quick cache, and only needed to load the database once at application startup to save on Cloud Database DTU hits. The webpage did load faster using the Singleton as a cache. A static class also worked for this scenario and is a little more straightforward. Either was ok for this scenario because I only changed the data about once per month, could restart the application when I wanted, and didn't have sessioned users on the site yet.
    However, once I want to add/change data in the database and want to reset the cache without an app restart, it is a dead-end; so it is not practical for many business production scenarios.
    I was just looking at 5-6 ways to cache and those were the quickest but most limited.

  • @slobodanmikaric2180
    @slobodanmikaric2180 Před 6 lety

    Singleton can be used in notification servers for mobile devices or others, when you always have one and only one instance to call to add or remove observers. :) thx Christopher Okhravi for clearing this out!

  • @vinoddurge8600
    @vinoddurge8600 Před 7 lety

    Great Series...Thanks for making those video ... waiting for more videos.

  • @flereoussarg
    @flereoussarg Před 6 lety

    Dude I really love your videos! Keep up the great work :)

  • @gurituna
    @gurituna Před 6 lety +1

    Excellent i have a java architecture certificate exam within 3 months. You made me clear with the design pattern. Many thanks. Bless you

    • @ChristopherOkhravi
      @ChristopherOkhravi  Před 6 lety +1

      +gokhan tuncel I'm glad to hear. Thank you very much for sharing and best of luck on the exam :)

  • @emskiee5330
    @emskiee5330 Před 5 lety +7

    I love Singleton in Unity. Very handy for Manager objects.

    • @TheLucausi
      @TheLucausi Před 4 lety +1

      It could become your worse nightmare xD

    • @emskiee5330
      @emskiee5330 Před 4 lety

      @@TheLucausi I've actually seen it unfold before me when the project I am working on became large. The Manager became this class with lots of states. Singleton, despite being great for Manager objects, should still be used sparingly :D

  • @radekp9851
    @radekp9851 Před 7 lety +196

    if one is a religious fanatic and assembles a God class, singleton pattern seems like an obvious choice :)

    • @ChristopherOkhravi
      @ChristopherOkhravi  Před 7 lety +16

      +Radek P This comment is quite simply hilarious :D :D

    • @pradeeph2000
      @pradeeph2000 Před 7 lety +10

      Radek P LOL!!! For Indian Hindu fanatic it's probably a fly weight pattern with millions of fly weights

    • @timmyers9798
      @timmyers9798 Před 5 lety +14

      Unless you have more than one god, then you have to refactor the whole universe.

    • @Quynn-Oneal
      @Quynn-Oneal Před 5 lety +4

      have you ever heard about Polytheism?

    • @uzil24
      @uzil24 Před 5 lety +8

      don't you mean polymorphism? ;-)

  • @MultiAkash1988
    @MultiAkash1988 Před 4 lety

    Love u sir, U make design pattern so easy

  • @stefanoforgiarini339
    @stefanoforgiarini339 Před 5 lety

    Excellent explanation Cristopher! Only one thing to note: what happens in a multi-threaded environment? It may happen that two different threads call the getInstance() method and because of this, more than one instance of the Singleton class is created. The only way to ensure a single instance is to add the synchronized in the getInstance method signature or (it would be better), synchronize the block of code in which we check if the instance is null (the if statement).
    Congrats for your videos!

  • @praveennampelly3559
    @praveennampelly3559 Před 2 lety

    Superb man, you explained very well. I really got lot of interest on design patterns. Thank you so much I leant a lot from your video's.

  • @firstname32yearsago65
    @firstname32yearsago65 Před 5 lety

    It’s very helpful, thanks

  • @aminebouita7185
    @aminebouita7185 Před 4 lety

    Best explanation, thanks a lot

  • @sitenepal7946
    @sitenepal7946 Před 7 lety +3

    I was waiting for this one :) wow it's wonderful

  • @sharaddabhi493
    @sharaddabhi493 Před 2 lety

    Great Explanation!

  • @maheshgangadhar4055
    @maheshgangadhar4055 Před 5 lety

    Very good explanation.. really help for me..