Diff. between singleton class and static class

G

Guest

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
 
J

Jon Skeet [C# MVP]

DBA said:
What is the diff. between a singleton class and a static class in C#?

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

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

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,
 
N

Nicholas Paldino [.NET/C# MVP]

Ignacio,

The statement:
first the currently there is no a way to declare a class static

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).
 
J

Jonathan Allen

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

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

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 said:
Ignacio,

The statement:
first the currently there is no a way to declare a class static

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]
- (e-mail address removed)


Ignacio Machin ( .NET/ C# MVP ) said:
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,
 
G

Guest

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
 
M

mdb

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

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(IWorkInterface iwi)
{
iwi.DoSomeWork();
}

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

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

// here i'm passing a different singleton
StartWork(singletonB);
}
 
J

Jeff Louie

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
 
J

Jon Skeet [C# MVP]

Jeff Louie said:
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.

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

There _are_ advantages to the Singleton pattern and they include:

3) Allows sub-classing.

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

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

Hi,


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.

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,
 
I

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

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,
 
J

Jon Skeet [C# MVP]

<"Ignacio Machin \( .NET/ C# MVP \)" <ignacio.machin AT
dot.state.fl.us> said:
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
}
}

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.)
 
J

Jeff Louie

Hi John.. In line.
Certainly the GoF book defines a singleton in terms of only providing
one
instance.<

That is the "Intent", but one of the "Consequences" is "4. Permits a
variable
number of instances." GoF pp 128.
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.<

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
 
J

Jon Skeet [C# MVP]

Jeff Louie said:
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.

See my reply to Ignacio - the normal singleton pattern is very elegant
in enforcing a single instance without ever having to actually check in
a constructor that it hasn't been constructed before, etc. With
subclassing some of that elegance goes away.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top