DBA
Hi All,
What is the diff. between a singleton class and a static class in C#?
Nov 17 '05 #1
Subscribe Reply
15 63896
- 1
- 2
- >
KH
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:
Hi All,What is the diff. between a singleton class and a static class in C#?
Nov 17 '05 #2
Jon Skeet [C# MVP]
DBA <DB*@discussion s.microsoft.com > wrote:
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.
--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #3
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,
--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
"DBA" <DB*@discussion s.microsoft.com > wrote in message
news:D4******** *************** ***********@mic rosoft.com...
Hi All,What is the diff. between a singleton class and a static class in C#?
Nov 17 '05 #4
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).--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m
"Ignacio Machin ( .NET/ C# MVP )" <ignacio.mach in AT dot.state.fl.us > wrote
in message news:uI******** ******@TK2MSFTN GP15.phx.gbl... 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" <DB*@discussion s.microsoft.com > wrote in message
news:D4******** *************** ***********@mic rosoft.com...Hi All,What is the diff. between a singleton class and a static class in C#?
Nov 17 '05 #5
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.
--
Jonathan Allen
"Ignacio Machin ( .NET/ C# MVP )" <ignacio.mach in AT dot.state.fl.us > wrote
in message news:uI******** ******@TK2MSFTN GP15.phx.gbl...
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" <DB*@discussion s.microsoft.com > wrote in message
news:D4******** *************** ***********@mic rosoft.com...Hi All,What is the diff. between a singleton class and a static class in C#?
Nov 17 '05 #6
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 [.NET/C# MVP]" <mv*@spam.guard .caspershouse.c om> wrote in
message news:er******** ******@TK2MSFTN GP14.phx.gbl...
Ignacio,The statement:
first the currently there is no a way to declare a class staticIs 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]
- mv*@spam.guard. caspershouse.co m
"Ignacio Machin ( .NET/ C# MVP )" <ignacio.mach in AT dot.state.fl.us >
wrote in message news:uI******** ******@TK2MSFTN GP15.phx.gbl...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" <DB*@discussion s.microsoft.com > wrote in message
news:D4******** *************** ***********@mic rosoft.com...Hi All,What is the diff. between a singleton class and a static class in C#?
Nov 17 '05 #7
DBA
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:
DBA <DB*@discussion s.microsoft.com > wrote: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.
--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #8
mdb
=?Utf-8?B?REJB?= <DB*@discussion s.microsoft.com > wrote in
news:BE******** *************** ***********@mic rosoft.com:
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(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
Nov 17 '05 #9
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
*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #10
- 1
- 2
- >
This thread has been closed and replies have been disabled. Please start a new discussion.
Similar topics
9 2306
by: Tim Clacy |last post by: Would some kind soul suggest a pre-processor test for the C++ language revision whereby class static variables were specified to refer to the same instance? Specifically, the following Singleton template will work with some compilers but not with older ones (because every module that includes the header gets its own unique static 'instance'): template<typename T> struct Singleton { static T& Instance() { static T instance; return... C / C++ |
5 5612 Singleton vs Static Methods by: Jake |last post by: I'm just getting into design patterns and am not sure I fully understand the usefulness of the singleton. I know you can use it to ensure that you only have one instance of a class, but why would you do that rather then just using static methods on your class. Any input would be great. Thank you, Jake .NET Framework |
7 2187 Singleton pattern vs Class with purely static members by: Atul Malaviya |last post by: >From a design/usability perspective. When will one use a singleton pattern and when a class with purely static members? What are the pros and cons? I have inherited a code base which is full of both these and I am a bit confused on this count. Singleton insures one object of a class in the application. A class with purely static members and a private constructor also strives to C# / C Sharp |
7 2394 Static Class by: Jon Vaughan |last post by: I have a piece of code that I want to run on a Pocket Pc, I have written a data class that will store the small amount of data that is required for the program. As this class will be used via a few forms in the program, what the best way to setup this class - Static ? and if so where do I enter the setup for the initial fetch, as at the moment its in the constructor, i'm right in thinking there is no constructor in a static class. Thanks C# / C Sharp |
3 2534 Singleton vs Static. by: Quantum |last post by: Hi, What is the difference between a singleton class and a static class? From what I can tell, they both offer the same functionality, i.e. only one copy of a class. Thanks, Q C / C++ |
5 2770 static class ...err.. pointer by: evaristobo |last post by: i'm a bit confused here, a pointer is something aiming to an object, but a static class is not an object, nevertheless i would like to have the possibility of doing something like handling an HashTable and getting from it a pointer to a static class : ( (classStatic)myHash("classStatic") ).staticMethod() ....is this possible, or i'm i short on reading? C# / C Sharp |
13 20762 "inherit" from a static class by: learning |last post by: Hi I have a static class written by other team which encapsulates a database instance. but I need to extend it to incldue other things. I know that C# static class is sealed and can;t be inherited & I don't want to copy + paste code. How can I inherit those member variables? Thanks C# / C Sharp |
4 2821 Singleton and static function by: John Doe |last post by: Hi, I have a singleton class defined like this : class UIManager : public CSingleton<UIManager>, public CObject { protected: DECLARE_DYNAMIC(UIManager) friend class CSingleton<UIManager>; C / C++ |
3 3896 static classes, nested class, public class by: puzzlecracker |last post by: Would you quickly remind me the difference between, regular class, static class, and nested class? Thanks C# / C Sharp |
8428
What is ONU? by: marktang |last post by: ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of... General |
8341 Changing the language in Windows 10 by: Hystou |last post by: Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,... Windows Server |
8851
Problem With Comparison Operator <=> in G++ by: Oralloy |last post by: Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in... C / C++ |
8754
Maximizing Business Potential: The Nexus of Website Design and Digital Marketing by: jinu1996 |last post by: In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is... Online Marketing |
1 8542 The easy way to turn off automatic updates for Windows 10/11 by: Hystou |last post by: Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,... Windows Server |
8630
Discussion: How does Zigbee compare with other wireless protocols in smart home applications? by: tracyyun |last post by: Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some... General |
5650 Couldnt get equations in html when convert word .docx file to html file in C#. by: conductexam |last post by: I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();... C# / C Sharp |
4343 Windows Forms - .Net 8.0 by: adsilva |last post by: A Windows Forms form does not have the event Unload, like VB6. What one acts like? Visual Basic .NET |
2 1984
How to add payments to a PHP MySQL app. by: muto222 |last post by: How can i add a mobile payment intergratation into php mysql website. PHP |