Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. Design and Architecture
  4. singleton pattern example

singleton pattern example

Scheduled Pinned Locked Moved Design and Architecture
designregexarchitecturetutorial
23 Posts 9 Posters 14 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • L led mike

    satyaki mishra wrote:

    one of the case you can use singleton pattern is to create a connection for your data base application.

    I don't believe that statement is particualrly helpful

    D Offline
    D Offline
    DavidNohejl
    wrote on last edited by
    #5

    And it's quite controversial use.


    [My Blog]
    "Visual studio desperately needs some performance improvements. It is sometimes almost as slow as eclipse." - Rüdiger Klaehn
    "Real men use mspaint for writing code and notepad for designing graphics." - Anna-Jayne Metcalfe

    L 1 Reply Last reply
    0
    • D DavidNohejl

      And it's quite controversial use.


      [My Blog]
      "Visual studio desperately needs some performance improvements. It is sometimes almost as slow as eclipse." - Rüdiger Klaehn
      "Real men use mspaint for writing code and notepad for designing graphics." - Anna-Jayne Metcalfe

      L Offline
      L Offline
      led mike
      wrote on last edited by
      #6

      dnh wrote:

      And it's quite controversial use.

      What use? His post is completely absent any use model, or any other contextual references, and therefore not helpful.

      D 1 Reply Last reply
      0
      • L led mike

        dnh wrote:

        And it's quite controversial use.

        What use? His post is completely absent any use model, or any other contextual references, and therefore not helpful.

        D Offline
        D Offline
        DavidNohejl
        wrote on last edited by
        #7

        "one of the case you can use singleton pattern is to create a connection for your data base application." Ok, if I was asking about singletons this wouldn't help me. In that I agree with you. But I believe that he is talking about scenario when you have class that manages connection to db, and creates connection in constructor. If that class is singleton, only one instance is created, so only one connection is created (which is usually very expensive operation). But then there's a pooling and you will have connection opened for whole lifetime of the singleton object, sometime you'll connect to db even when you don't need to etc. Which is why I say this is not the supercleanest use of singleton pattern.


        [My Blog]
        "Visual studio desperately needs some performance improvements. It is sometimes almost as slow as eclipse." - Rüdiger Klaehn
        "Real men use mspaint for writing code and notepad for designing graphics." - Anna-Jayne Metcalfe

        L 1 Reply Last reply
        0
        • D DavidNohejl

          "one of the case you can use singleton pattern is to create a connection for your data base application." Ok, if I was asking about singletons this wouldn't help me. In that I agree with you. But I believe that he is talking about scenario when you have class that manages connection to db, and creates connection in constructor. If that class is singleton, only one instance is created, so only one connection is created (which is usually very expensive operation). But then there's a pooling and you will have connection opened for whole lifetime of the singleton object, sometime you'll connect to db even when you don't need to etc. Which is why I say this is not the supercleanest use of singleton pattern.


          [My Blog]
          "Visual studio desperately needs some performance improvements. It is sometimes almost as slow as eclipse." - Rüdiger Klaehn
          "Real men use mspaint for writing code and notepad for designing graphics." - Anna-Jayne Metcalfe

          L Offline
          L Offline
          led mike
          wrote on last edited by
          #8

          dnh wrote:

          Which is why I say this is not the supercleanest use of singleton pattern.

          It's a perfectly fine design when the use model is a single user desktop application connecting to a desktop database. Your post also lacks specific use model information required to draw any conclusion as to the accuracy of your statement.

          D 1 Reply Last reply
          0
          • L led mike

            dnh wrote:

            Which is why I say this is not the supercleanest use of singleton pattern.

            It's a perfectly fine design when the use model is a single user desktop application connecting to a desktop database. Your post also lacks specific use model information required to draw any conclusion as to the accuracy of your statement.

            D Offline
            D Offline
            DavidNohejl
            wrote on last edited by
            #9

            led mike wrote:

            It's a perfectly fine design when

            Isn't that little word "when", and what follows it, proving my point? (but then again, I've just came from work :zzz:)


            [My Blog]
            "Visual studio desperately needs some performance improvements. It is sometimes almost as slow as eclipse." - Rüdiger Klaehn
            "Real men use mspaint for writing code and notepad for designing graphics." - Anna-Jayne Metcalfe

            1 Reply Last reply
            0
            • V Vinay Dornala

              hi everybody, Iam new to design pattern concept , I want to know in which scenario we are using singleton pattern in our appl. I need exact scenario because i had some examples and gone the theory in books i want applicable knowledge in application development. Thanks in advance for replay,

              C Offline
              C Offline
              Colin Angus Mackay
              wrote on last edited by
              #10

              shakeela wrote:

              I want to know in which scenario we are using singleton pattern

              When dumped by ones girlfriend or significant other.


              Upcoming FREE developer events: * Glasgow: Agile in the Enterprise Vs. ISVs, db4o: An Embeddable Database Engine for Object-Oriented Environments, Mock Objects, SQL Server CLR Integration, Reporting Services ... My website

              1 Reply Last reply
              0
              • V Vinay Dornala

                hi everybody, Iam new to design pattern concept , I want to know in which scenario we are using singleton pattern in our appl. I need exact scenario because i had some examples and gone the theory in books i want applicable knowledge in application development. Thanks in advance for replay,

                C Offline
                C Offline
                Colin Angus Mackay
                wrote on last edited by
                #11

                shakeela wrote:

                I want to know in which scenario we are using singleton pattern in our appl

                Here is one scenario[^] But, my plans for this series will remove the singleton pattern later.


                Upcoming FREE developer events: * Glasgow: Agile in the Enterprise Vs. ISVs, db4o: An Embeddable Database Engine for Object-Oriented Environments, Mock Objects, SQL Server CLR Integration, Reporting Services ... My website

                1 Reply Last reply
                0
                • V Vinay Dornala

                  hi everybody, Iam new to design pattern concept , I want to know in which scenario we are using singleton pattern in our appl. I need exact scenario because i had some examples and gone the theory in books i want applicable knowledge in application development. Thanks in advance for replay,

                  U Offline
                  U Offline
                  Urs Enzler
                  wrote on last edited by
                  #12

                  I consider singletons as evil! If there has to exist really one one instance of a class then I use a manager pattern (don't know if this patter has a real pattern name): I request the "singleton" from a Manager that will return me the instance. Depending on configuration and other things it will return me a singleton or a new instance. Furthermore I request interfaces which allows the replacement of "singletons" either for testing (mocks) or changed requirements or if it is a base functionality that is used in different projects. Much more flexible.

                  -^-^-^-^-^- no risk no funk ................... please vote ------>

                  C L 2 Replies Last reply
                  0
                  • V Vinay Dornala

                    hi everybody, Iam new to design pattern concept , I want to know in which scenario we are using singleton pattern in our appl. I need exact scenario because i had some examples and gone the theory in books i want applicable knowledge in application development. Thanks in advance for replay,

                    H Offline
                    H Offline
                    hotcodeking
                    wrote on last edited by
                    #13

                    Hi Dear as theory says singleton use is for making one instance available throughout the life time of application As far as scenario is concerned the dbconnection is bad one as some one said becos of pooling. You can think of salary being credited and debited to employee accounts in banks. you can make sure this operation is implemented using singleton class can also make sure only the manager or single person in bank has access to this class.

                    Gokul- MCSD:MCAD:MCP - Technical Lead - GFT INDIA

                    1 Reply Last reply
                    0
                    • U Urs Enzler

                      I consider singletons as evil! If there has to exist really one one instance of a class then I use a manager pattern (don't know if this patter has a real pattern name): I request the "singleton" from a Manager that will return me the instance. Depending on configuration and other things it will return me a singleton or a new instance. Furthermore I request interfaces which allows the replacement of "singletons" either for testing (mocks) or changed requirements or if it is a base functionality that is used in different projects. Much more flexible.

                      -^-^-^-^-^- no risk no funk ................... please vote ------>

                      C Offline
                      C Offline
                      Colin Angus Mackay
                      wrote on last edited by
                      #14

                      Sounds like you are using the Factory Pattern to generate the singleton.

                      Urs Enzler wrote:

                      Furthermore I request interfaces which allows the replacement of "singletons" either for testing (mocks)

                      Very useful for that.


                      Upcoming FREE developer events: * Glasgow: Agile in the Enterprise Vs. ISVs, db4o: An Embeddable Database Engine for Object-Oriented Environments, Mock Objects, SQL Server CLR Integration, Reporting Services ... My website

                      U 1 Reply Last reply
                      0
                      • C Colin Angus Mackay

                        Sounds like you are using the Factory Pattern to generate the singleton.

                        Urs Enzler wrote:

                        Furthermore I request interfaces which allows the replacement of "singletons" either for testing (mocks)

                        Very useful for that.


                        Upcoming FREE developer events: * Glasgow: Agile in the Enterprise Vs. ISVs, db4o: An Embeddable Database Engine for Object-Oriented Environments, Mock Objects, SQL Server CLR Integration, Reporting Services ... My website

                        U Offline
                        U Offline
                        Urs Enzler
                        wrote on last edited by
                        #15

                        I'm not sure what the exact name is, because a Factory is something that instanciates objects for me, but a manager does that and manages the instance. If I request the same interface I'll get the same instance.

                        -^-^-^-^-^- no risk no funk ................... please vote ------>

                        1 Reply Last reply
                        0
                        • U Urs Enzler

                          I consider singletons as evil! If there has to exist really one one instance of a class then I use a manager pattern (don't know if this patter has a real pattern name): I request the "singleton" from a Manager that will return me the instance. Depending on configuration and other things it will return me a singleton or a new instance. Furthermore I request interfaces which allows the replacement of "singletons" either for testing (mocks) or changed requirements or if it is a base functionality that is used in different projects. Much more flexible.

                          -^-^-^-^-^- no risk no funk ................... please vote ------>

                          L Offline
                          L Offline
                          led mike
                          wrote on last edited by
                          #16

                          Urs Enzler wrote:

                          I consider singletons as evil!

                          It's just a "Creational Pattern", there are many, your situation calls for a different one. That does not provide reasoning for declaring the Singleton to be "Evil".  However there are plenty of arguments about it on the WikiWikiWeb.

                          U 1 Reply Last reply
                          0
                          • L led mike

                            Urs Enzler wrote:

                            I consider singletons as evil!

                            It's just a "Creational Pattern", there are many, your situation calls for a different one. That does not provide reasoning for declaring the Singleton to be "Evil".  However there are plenty of arguments about it on the WikiWikiWeb.

                            U Offline
                            U Offline
                            Urs Enzler
                            wrote on last edited by
                            #17

                            Yes of course, I'm a bit exaggerating :) The main reason I'm not a fan of the singleton pattern is because it is overused. 1) The decision that something exists only once in an application is a very final one. Normally singletons are very basic things in an application (a logger for example). And if that changes (happend about three times to a project I was working in) it is very hard to refactor (because of point 2) 2) It is often the case that projects using singletons are not loosly coupled: components reference the singleton by something like MySingletonClass.Instance. I consider this very limiting. In an earlier post I mentioned that I use a Manager pattern (or Factory pattern) that allows me to exchagne the real object behind the "singleton" for example for testing (mocks). 3) In a framework or in a base components library, you should definitly not use singletons because they can not be replaced by project specific instances. Because of these reasons I prefer using a manager pattern (Factory pattern) because it is not really more complicated but very much more flexible and not limited. And as a final word: yes there are situations where the singleton pattern is adequat, but they are seldom in my eyes or there exists a better pattern for the scenario.

                            -^-^-^-^-^- no risk no funk ................... please vote ------>

                            L 1 Reply Last reply
                            0
                            • U Urs Enzler

                              Yes of course, I'm a bit exaggerating :) The main reason I'm not a fan of the singleton pattern is because it is overused. 1) The decision that something exists only once in an application is a very final one. Normally singletons are very basic things in an application (a logger for example). And if that changes (happend about three times to a project I was working in) it is very hard to refactor (because of point 2) 2) It is often the case that projects using singletons are not loosly coupled: components reference the singleton by something like MySingletonClass.Instance. I consider this very limiting. In an earlier post I mentioned that I use a Manager pattern (or Factory pattern) that allows me to exchagne the real object behind the "singleton" for example for testing (mocks). 3) In a framework or in a base components library, you should definitly not use singletons because they can not be replaced by project specific instances. Because of these reasons I prefer using a manager pattern (Factory pattern) because it is not really more complicated but very much more flexible and not limited. And as a final word: yes there are situations where the singleton pattern is adequat, but they are seldom in my eyes or there exists a better pattern for the scenario.

                              -^-^-^-^-^- no risk no funk ................... please vote ------>

                              L Offline
                              L Offline
                              led mike
                              wrote on last edited by
                              #18

                              Urs Enzler wrote:

                              The main reason I'm not a fan of the singleton pattern is because it is overused.

                              :laugh::laugh::laugh: not laughing at you. It made me think, well duh software development is overused misused, and pretty much everything in it is misused. :-D You should see how some of my peers abused the word "Agile" :laugh::laugh::laugh: :-D :) :| :( :^) :((:((:((

                              Urs Enzler wrote:

                              Because of these reasons I prefer using a manager pattern (Factory pattern)

                              You probably know this but there are many more creational patterns[^]

                              U 1 Reply Last reply
                              0
                              • L led mike

                                Urs Enzler wrote:

                                The main reason I'm not a fan of the singleton pattern is because it is overused.

                                :laugh::laugh::laugh: not laughing at you. It made me think, well duh software development is overused misused, and pretty much everything in it is misused. :-D You should see how some of my peers abused the word "Agile" :laugh::laugh::laugh: :-D :) :| :( :^) :((:((:((

                                Urs Enzler wrote:

                                Because of these reasons I prefer using a manager pattern (Factory pattern)

                                You probably know this but there are many more creational patterns[^]

                                U Offline
                                U Offline
                                Urs Enzler
                                wrote on last edited by
                                #19

                                led mike wrote:

                                You probably know this but there are many more creational patterns[^]

                                Unfortunately, this page does not mention the kind of pattern we are using. Maybe this is because it is actually a Factory (instance creation) but with managing functionality :) May the crusade for good design continue ...

                                -^-^-^-^-^- no risk no funk ................... please vote ------>

                                L 1 Reply Last reply
                                0
                                • U Urs Enzler

                                  led mike wrote:

                                  You probably know this but there are many more creational patterns[^]

                                  Unfortunately, this page does not mention the kind of pattern we are using. Maybe this is because it is actually a Factory (instance creation) but with managing functionality :) May the crusade for good design continue ...

                                  -^-^-^-^-^- no risk no funk ................... please vote ------>

                                  L Offline
                                  L Offline
                                  led mike
                                  wrote on last edited by
                                  #20

                                  Urs Enzler wrote:

                                  but with managing functionality

                                  "managing" would be structural.

                                  Urs Enzler wrote:

                                  Depending on configuration and other things it will return me a singleton or a new instance.

                                  It is difficult to understand that with any certainty. Perhaps you are using both Factory and Flyweight[^] Patterns. Or perhaps you are referring to a higher level abstraction of both into a Composite or Facade. I can't tell.

                                  U 1 Reply Last reply
                                  0
                                  • L led mike

                                    Urs Enzler wrote:

                                    but with managing functionality

                                    "managing" would be structural.

                                    Urs Enzler wrote:

                                    Depending on configuration and other things it will return me a singleton or a new instance.

                                    It is difficult to understand that with any certainty. Perhaps you are using both Factory and Flyweight[^] Patterns. Or perhaps you are referring to a higher level abstraction of both into a Composite or Facade. I can't tell.

                                    U Offline
                                    U Offline
                                    Urs Enzler
                                    wrote on last edited by
                                    #21

                                    Hmm, I'd say it is as you say a higher level of abstraction and containing several individual design patterns. I think I should write an article about that, that would make the discussion easier ;)

                                    -^-^-^-^-^- no risk no funk ................... please vote ------>

                                    1 Reply Last reply
                                    0
                                    • V Vinay Dornala

                                      hi everybody, Iam new to design pattern concept , I want to know in which scenario we are using singleton pattern in our appl. I need exact scenario because i had some examples and gone the theory in books i want applicable knowledge in application development. Thanks in advance for replay,

                                      E Offline
                                      E Offline
                                      ElSpinos
                                      wrote on last edited by
                                      #22

                                      Greetings Shakeela, The Singleton design pattern serves to describe an implementation that restricts instantiation of a class to one object, in other words no copies or additional references. I've created a Singleton instantiate for you here to experiment with and get an idea of my description above. the singleton design pattern also belongs to the Creational Patterns group which consist of the following additional design patterns: o Abstract factory pattern: centralize decision of what factory to instantiate o Factory method pattern: centralize creation of an object of a specific type choosing one of several implementations o Builder pattern: separate the construction of a complex object from its representation so that the same construction process can create different representations o Lazy initialization pattern: tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed o Object pool: avoid expensive acquisition and release of resources by recycling objects that are no longer in use o Prototype pattern: used when the inherent cost of creating a new object in the standard way (e.g., using the 'new' keyword) is prohibitively expensive for a given application The singleton class you can experiment with: /// Any type with a public and parameterless constructor. public sealed class SingletonCreator where Type : class, new() { #region Private declarations /// /// The instance to retain after creation /// private static Type instance; #endregion #region Properties /// /// A lazy instance instantiator property. It will test for the existence of an object and return that reference otherwise it will create a new object. /// /// An singleton instance of type "Type". public static Type GetInstance() { lock (typeof(Type)) { if (instance == null) { instance = new Type(); } return instance; } } #endregion } Usage: // This will always create an instance it it doesn’t exist or return the // existin reference if it was previously called. MyClass myClass = SingletonCreator<MyClass>.GetInstance(); I hope this helps you in your quest to learn design patterns ;) Have an awesome weekend...

                                      Fernando Mendes Senior .NET Developer, Architect

                                      1 Reply Last reply
                                      0
                                      • V Vinay Dornala

                                        hi everybody, Iam new to design pattern concept , I want to know in which scenario we are using singleton pattern in our appl. I need exact scenario because i had some examples and gone the theory in books i want applicable knowledge in application development. Thanks in advance for replay,

                                        E Offline
                                        E Offline
                                        etkid84
                                        wrote on last edited by
                                        #23

                                        singletons are used when it only makes sense to have exactly one and only one of them... i am not sure the impact singletons have on multi-threaded apps either, you might want to do some research in that area as well. design patterns are an interesting concept... i always stick to the kiss principle.. and avoid over-engineering my code. sometimes you can get into trouble with singletons, because sometimes they are implemented with private a constructor and destructor, and some example implementations you find on the web have nearly undetectable flaws ... there are variations to this theme between java and c++, and i am not sure about python (or whether you even need to do it in python). be cautious and judicious in your decision making, kind regards,

                                        David

                                        1 Reply Last reply
                                        0
                                        Reply
                                        • Reply as topic
                                        Log in to reply
                                        • Oldest to Newest
                                        • Newest to Oldest
                                        • Most Votes


                                        • Login

                                        • Don't have an account? Register

                                        • Login or register to search.
                                        • First post
                                          Last post
                                        0
                                        • Categories
                                        • Recent
                                        • Tags
                                        • Popular
                                        • World
                                        • Users
                                        • Groups