Diff. between singleton class and static class

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • DBA

    Diff. between singleton class and static class

    Hi All,

    What is the diff. between a singleton class and a static class in C#?
  • KH

    #2
    RE: Diff. between singleton class and static class

    A static class does not allow an instance of itself to be created by anything
    other than itself - it has no public ctors:

    class T
    {
    private T() { }

    public static T Get() { return new T(); }
    };

    T t1 = new T(); // Error, no public constructor
    T t2 = T.Get(); // Ok
    T t3 = T.Get(); // Ok; returns another instance of T

    A singleton allows only one instance of the class to ever be created:

    class S
    {
    private S() { }

    private static S instance = new S();

    public static S Get() { return S.instance; }
    };

    S s1 = new S(); // Error, no public constructor
    S s2 = S.Get(); // Ok; always returns the same instnace
    S s3 = S.Get(); // Ok; returns the same instance as s2




    "DBA" wrote:
    [color=blue]
    > Hi All,
    >
    > What is the diff. between a singleton class and a static class in C#?[/color]

    Comment

    • Jon Skeet [C# MVP]

      #3
      Re: Diff. between singleton class and static class

      DBA <DBA@discussion s.microsoft.com > wrote:[color=blue]
      > What is the diff. between a singleton class and a static class in C#?[/color]

      A singleton allows access to a single created instance - that instance
      (or rather, a reference to that instance) can be passed as a parameter
      to other methods, and treated as a normal object.

      A static class allows only static methods.

      --
      Jon Skeet - <skeet@pobox.co m>
      Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

      If replying to the group, please do not mail me too

      Comment

      • Ignacio Machin \( .NET/ C# MVP \)

        #4
        Re: Diff. between singleton class and static class

        Hi,

        first the currently there is no a way to declare a class static, you do it
        implicitely by declaring static all the members of it. The members will
        exist as long as the Appdomain does.

        A singleton is a "normal" class with the only difference that the
        constructor is private, hence the only way to "create" an instance is using
        the property/method that return the instance. If needed you can also declare
        a method that dispose the instance, so it can be recreated again when
        needed.


        cheers,

        --
        Ignacio Machin,
        ignacio.machin AT dot.state.fl.us
        Florida Department Of Transportation



        "DBA" <DBA@discussion s.microsoft.com > wrote in message
        news:D4B6963F-3698-4860-9483-3B2236772735@mi crosoft.com...[color=blue]
        > Hi All,
        >
        > What is the diff. between a singleton class and a static class in C#?[/color]


        Comment

        • Nicholas Paldino [.NET/C# MVP]

          #5
          Re: Diff. between singleton class and static class

          Ignacio,

          The statement:
          [color=blue]
          > first the currently there is no a way to declare a class static[/color]

          Is not true. In the current beta release of C# 2.0, there is support
          for static classes, where all of the members must be static (and the
          compiler issues a warning if any of the members are not).

          --
          - Nicholas Paldino [.NET/C# MVP]
          - mvp@spam.guard. caspershouse.co m


          "Ignacio Machin ( .NET/ C# MVP )" <ignacio.mach in AT dot.state.fl.us > wrote
          in message news:uIcXfctZFH A.2076@TK2MSFTN GP15.phx.gbl...[color=blue]
          > Hi,
          >
          > first the currently there is no a way to declare a class static, you do it
          > implicitely by declaring static all the members of it. The members will
          > exist as long as the Appdomain does.
          >
          > A singleton is a "normal" class with the only difference that the
          > constructor is private, hence the only way to "create" an instance is
          > using the property/method that return the instance. If needed you can also
          > declare a method that dispose the instance, so it can be recreated again
          > when needed.
          >
          >
          > cheers,
          >
          > --
          > Ignacio Machin,
          > ignacio.machin AT dot.state.fl.us
          > Florida Department Of Transportation
          >
          >
          >
          > "DBA" <DBA@discussion s.microsoft.com > wrote in message
          > news:D4B6963F-3698-4860-9483-3B2236772735@mi crosoft.com...[color=green]
          >> Hi All,
          >>
          >> What is the diff. between a singleton class and a static class in C#?[/color]
          >
          >[/color]


          Comment

          • Jonathan Allen

            #6
            Re: Diff. between singleton class and static class

            You can declare the entire class as static in VB. I believe the next version
            of C# will also have that ability, but I'm not certain.

            The only reasons (that I know) to use a singleton is if you need to pass it
            to a function call. For example, an IComparer class.


            --
            Jonathan Allen


            "Ignacio Machin ( .NET/ C# MVP )" <ignacio.mach in AT dot.state.fl.us > wrote
            in message news:uIcXfctZFH A.2076@TK2MSFTN GP15.phx.gbl...[color=blue]
            > Hi,
            >
            > first the currently there is no a way to declare a class static, you do it
            > implicitely by declaring static all the members of it. The members will
            > exist as long as the Appdomain does.
            >
            > A singleton is a "normal" class with the only difference that the
            > constructor is private, hence the only way to "create" an instance is
            > using the property/method that return the instance. If needed you can also
            > declare a method that dispose the instance, so it can be recreated again
            > when needed.
            >
            >
            > cheers,
            >
            > --
            > Ignacio Machin,
            > ignacio.machin AT dot.state.fl.us
            > Florida Department Of Transportation
            >
            >
            >
            > "DBA" <DBA@discussion s.microsoft.com > wrote in message
            > news:D4B6963F-3698-4860-9483-3B2236772735@mi crosoft.com...[color=green]
            >> Hi All,
            >>
            >> What is the diff. between a singleton class and a static class in C#?[/color]
            >
            >[/color]


            Comment

            • Ignacio Machin \( .NET/ C# MVP \)

              #7
              Re: Diff. between singleton class and static class

              Hi,

              Yes, I meant that , just that I totally miswrote that sentence :)

              cheers,

              --
              Ignacio Machin,
              ignacio.machin AT dot.state.fl.us
              Florida Department Of Transportation



              "Nicholas Paldino [.NET/C# MVP]" <mvp@spam.guard .caspershouse.c om> wrote in
              message news:erdzBytZFH A.3648@TK2MSFTN GP14.phx.gbl...[color=blue]
              > Ignacio,
              >
              > The statement:
              >[color=green]
              >> first the currently there is no a way to declare a class static[/color]
              >
              > Is not true. In the current beta release of C# 2.0, there is support
              > for static classes, where all of the members must be static (and the
              > compiler issues a warning if any of the members are not).
              >
              > --
              > - Nicholas Paldino [.NET/C# MVP]
              > - mvp@spam.guard. caspershouse.co m
              >
              >
              > "Ignacio Machin ( .NET/ C# MVP )" <ignacio.mach in AT dot.state.fl.us >
              > wrote in message news:uIcXfctZFH A.2076@TK2MSFTN GP15.phx.gbl...[color=green]
              >> Hi,
              >>
              >> first the currently there is no a way to declare a class static, you do
              >> it implicitely by declaring static all the members of it. The members
              >> will exist as long as the Appdomain does.
              >>
              >> A singleton is a "normal" class with the only difference that the
              >> constructor is private, hence the only way to "create" an instance is
              >> using the property/method that return the instance. If needed you can
              >> also declare a method that dispose the instance, so it can be recreated
              >> again when needed.
              >>
              >>
              >> cheers,
              >>
              >> --
              >> Ignacio Machin,
              >> ignacio.machin AT dot.state.fl.us
              >> Florida Department Of Transportation
              >>
              >>
              >>
              >> "DBA" <DBA@discussion s.microsoft.com > wrote in message
              >> news:D4B6963F-3698-4860-9483-3B2236772735@mi crosoft.com...[color=darkred]
              >>> Hi All,
              >>>
              >>> What is the diff. between a singleton class and a static class in C#?[/color]
              >>
              >>[/color]
              >
              >[/color]


              Comment

              • DBA

                #8
                Re: Diff. between singleton class and static class

                KH, Jon Thank you for responses. One more question:
                When to use a singleton class and when to use a staic class? I think both
                has the same functionality

                "Jon Skeet [C# MVP]" wrote:
                [color=blue]
                > DBA <DBA@discussion s.microsoft.com > wrote:[color=green]
                > > What is the diff. between a singleton class and a static class in C#?[/color]
                >
                > A singleton allows access to a single created instance - that instance
                > (or rather, a reference to that instance) can be passed as a parameter
                > to other methods, and treated as a normal object.
                >
                > A static class allows only static methods.
                >
                > --
                > Jon Skeet - <skeet@pobox.co m>
                > http://www.pobox.com/~skeet
                > If replying to the group, please do not mail me too
                >[/color]

                Comment

                • mdb

                  #9
                  Re: Diff. between singleton class and static class

                  =?Utf-8?B?REJB?= <DBA@discussion s.microsoft.com > wrote in
                  news:BEBE8D12-F2B9-4B51-8E5E-F1DA36696DF9@mi crosoft.com:
                  [color=blue]
                  > KH, Jon Thank you for responses. One more question:
                  > When to use a singleton class and when to use a staic class? I think
                  > both has the same functionality
                  >[/color]

                  For one example, whenever you want to be able to pass the instance of the
                  class as a parameter to a function... Just because you have a
                  "singleton" class doesn't mean that there's only one singleton class
                  (although by definition there's only one instance of *each* of them)...
                  Such as...

                  public interface IWorkInterface
                  {
                  void DoSomeWork();
                  }

                  public SingletonA : IWorkInterface
                  {
                  .... singleton implementation ...
                  public void DoSomeWork() { ... }
                  }

                  public SingletonB : IWorkInterface
                  {
                  .... singleton implementation ...
                  public void DoSomeWork() { ... }
                  }

                  public void StartWork(IWork Interface iwi)
                  {
                  iwi.DoSomeWork( );
                  }

                  public void Main()
                  {
                  IWorkInterface singletonA = new SingletonA();
                  IWorkInterface singletonB = new SingletonB();

                  // here i'm passing the object - its a singleton
                  StartWork(singl etonA);

                  // here i'm passing a different singleton
                  StartWork(singl etonB);
                  }

                  --
                  -mdb

                  Comment

                  • Jeff Louie

                    #10
                    Re: Diff. between singleton class and static class


                    First, the Singleton Pattern generally creates a single instance of a
                    class, but
                    this is not absolute. In fact, you can argue that some of the
                    flexibility of the
                    Singleton Pattern is that it allows you the programmer to return more
                    than
                    one instance of a class at a later date without breaking the client
                    code. The
                    classic example is an expensive hardware resource. You implement this as
                    a
                    Singleton Pattern. Later, when you win the lottery you can purchase a
                    second
                    unit of this expensive hardware resource and recode the class factory to
                    return one of the two hardware controllers using load sharing. The
                    caller does
                    not know that there are now two units.

                    Perhaps it would help to think of where the code goes and how this could
                    help you understand the difference between static methods and fields and
                    a
                    Singleton Pattern.

                    In a Static call you have one set of static methods and fields in
                    memory. There
                    is no need for a pointer to the instance stack frame. Now let's go back
                    to the
                    classic Singleton where you have one instance of the class. Although the
                    code
                    for instance methods _appears_ to be copied for each instance so that
                    each
                    instance has BEHAVIOR, in reality the code for instance methods is
                    _shared_!
                    So the only real difference between Static calls and instance calls is
                    that
                    instance calls act on instance data and each instance has its own
                    separate
                    data in memory. But if you only have one instance then there is only one
                    copy
                    of instance data. SO, the only real difference between Static and a
                    single
                    instance is that there is a pointer to this to access the instance data.

                    There _are_ advantages to the Singleton pattern and they include:

                    1) Adds a level of indirection. This allows the creation of more than
                    one
                    instance of the class at a later date without breaking client code.
                    2) Encapsulates data and methods into a separate namespace, the
                    singleton
                    class.
                    3) Allows sub-classing.
                    4) Provides access control to the single instance.

                    Hope that helps.

                    Have fun storming the castle,
                    Jeff

                    *** Sent via Developersdex http://www.developersdex.com ***

                    Comment

                    • Jon Skeet [C# MVP]

                      #11
                      Re: Diff. between singleton class and static class

                      Jeff Louie <jeff_louie@yah oo.com> wrote:[color=blue]
                      > First, the Singleton Pattern generally creates a single instance of a
                      > class, but this is not absolute. In fact, you can argue that some of
                      > the flexibility of the Singleton Pattern is that it allows you the
                      > programmer to return more than one instance of a class at a later
                      > date without breaking the client code.[/color]

                      I'd argue that in that case it's a factory. Certainly the GoF book
                      defines a singleton in terms of only providing one instance. I agree
                      that using a singleton allows you to change it into a factory at a
                      later date without breaking client code though. (Assuming the client
                      code isn't relying on it being a singleton.)

                      <snip>
                      [color=blue]
                      > There _are_ advantages to the Singleton pattern and they include:[/color]

                      <snip>
                      [color=blue]
                      > 3) Allows sub-classing.[/color]

                      It allows the singleton to be a subclass of something else. The normal
                      patterns that ensure that only a single instance is ever created don't
                      work well with subclasses. It can be done, but it's somewhat messy.

                      --
                      Jon Skeet - <skeet@pobox.co m>
                      Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

                      If replying to the group, please do not mail me too

                      Comment

                      • Ignacio Machin \( .NET/ C# MVP \)

                        #12
                        Re: Diff. between singleton class and static class

                        Hi,


                        [color=blue]
                        >[color=green]
                        >> 3) Allows sub-classing.[/color]
                        >
                        > It allows the singleton to be a subclass of something else. The normal
                        > patterns that ensure that only a single instance is ever created don't
                        > work well with subclasses. It can be done, but it's somewhat messy.[/color]

                        Why messy?

                        It's the member who return the instance the one in charge of that, it could
                        work as a factory deciding at runtime an instance of what class to create
                        and return. Somewhere I saw a code like this:

                        public static SingletonClass GetInstance()
                        {
                        if ( instance == null )
                        {
                        //decide which class derived of SingletonClass to instantiate
                        return instance
                        }
                        }



                        cheers,

                        --
                        Ignacio Machin,
                        ignacio.machin AT dot.state.fl.us
                        Florida Department Of Transportation



                        Comment

                        • Ignacio Machin \( .NET/ C# MVP \)

                          #13
                          Re: Diff. between singleton class and static class

                          Hi,

                          Also there is the fact that you can control when to create the singleton,
                          even so you can create the singleton more than one time during the lifetime
                          of the app. The only thing that the singleton assure is that only one
                          instance exist at a given time, not that the same instance exist always.

                          cheers,

                          --
                          Ignacio Machin,
                          ignacio.machin AT dot.state.fl.us
                          Florida Department Of Transportation


                          "mdb" <m_b_r_a_y@c_t_ i_u_s_a__d0t__c om> wrote in message
                          news:Xns9668C15 B47A5Fmbrayctiu sacom@207.46.24 8.16...[color=blue]
                          > =?Utf-8?B?REJB?= <DBA@discussion s.microsoft.com > wrote in
                          > news:BEBE8D12-F2B9-4B51-8E5E-F1DA36696DF9@mi crosoft.com:
                          >[color=green]
                          >> KH, Jon Thank you for responses. One more question:
                          >> When to use a singleton class and when to use a staic class? I think
                          >> both has the same functionality
                          >>[/color]
                          >
                          > For one example, whenever you want to be able to pass the instance of the
                          > class as a parameter to a function... Just because you have a
                          > "singleton" class doesn't mean that there's only one singleton class
                          > (although by definition there's only one instance of *each* of them)...
                          > Such as...
                          >
                          > public interface IWorkInterface
                          > {
                          > void DoSomeWork();
                          > }
                          >
                          > public SingletonA : IWorkInterface
                          > {
                          > ... singleton implementation ...
                          > public void DoSomeWork() { ... }
                          > }
                          >
                          > public SingletonB : IWorkInterface
                          > {
                          > ... singleton implementation ...
                          > public void DoSomeWork() { ... }
                          > }
                          >
                          > public void StartWork(IWork Interface iwi)
                          > {
                          > iwi.DoSomeWork( );
                          > }
                          >
                          > public void Main()
                          > {
                          > IWorkInterface singletonA = new SingletonA();
                          > IWorkInterface singletonB = new SingletonB();
                          >
                          > // here i'm passing the object - its a singleton
                          > StartWork(singl etonA);
                          >
                          > // here i'm passing a different singleton
                          > StartWork(singl etonB);
                          > }
                          >
                          > --
                          > -mdb[/color]


                          Comment

                          • Jon Skeet [C# MVP]

                            #14
                            Re: Diff. between singleton class and static class

                            <"Ignacio Machin \( .NET/ C# MVP \)" <ignacio.mach in AT
                            dot.state.fl.us >> wrote:[color=blue][color=green][color=darkred]
                            > >> 3) Allows sub-classing.[/color]
                            > >
                            > > It allows the singleton to be a subclass of something else. The normal
                            > > patterns that ensure that only a single instance is ever created don't
                            > > work well with subclasses. It can be done, but it's somewhat messy.[/color]
                            >
                            > Why messy?
                            >
                            > It's the member who return the instance the one in charge of that, it could
                            > work as a factory deciding at runtime an instance of what class to create
                            > and return. Somewhere I saw a code like this:
                            >
                            > public static SingletonClass GetInstance()
                            > {
                            > if ( instance == null )
                            > {
                            > //decide which class derived of SingletonClass to instantiate
                            > return instance
                            > }
                            > }[/color]

                            In that case though, there's nothing to stop the derived class from
                            creating an instance of itself - or another derived class to derive
                            from the SingletonClass.

                            One of the benefits of the singleton pattern in its normal form is that
                            you can guarantee that the only thing that will create an instance of
                            the class is the class itself, because it only has a private
                            constructor. (Leaving reflection aside, of course.)

                            --
                            Jon Skeet - <skeet@pobox.co m>
                            Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

                            If replying to the group, please do not mail me too

                            Comment

                            • Jeff Louie

                              #15
                              Re: Diff. between singleton class and static class

                              Hi John.. In line.
                              [color=blue]
                              >Certainly the GoF book defines a singleton in terms of only providing[/color]
                              one
                              instance.<

                              That is the "Intent", but one of the "Consequenc es" is "4. Permits a
                              variable
                              number of instances." GoF pp 128.
                              [color=blue]
                              >It allows the singleton to be a subclass of something else. The normal[/color]
                              patterns that ensure that only a single instance is ever created don't
                              work well with subclasses. It can be done, but it's somewhat messy.<

                              Hmm. I don't understand why this is messy. In C# an interface can be
                              looked
                              at as subclassing where a concrete class implements an interface or
                              extends a
                              pure virtual class. The singleton GetInstance method can return an
                              interface
                              type or a method can take a singleton reference of an interface type
                              allowing
                              you to program to an interface. The supplier supplies a single instance
                              of an
                              object that implements the contract, the interface.

                              Regards,
                              Jeff

                              *** Sent via Developersdex http://www.developersdex.com ***

                              Comment

                              Working...