473,569 Members | 2,698 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Static classes vs Singletons (pt 2)

Following on from the other discussion, I have to just check something out
with reference to disposal of resources held in static fields.

I have a Persistence Framework that is 'globally accessible'. In Delphi, I
would use a class of static methods to enforce the singleton, and I added
static fields to hold things like the database connections, etc.

This worked fine in Delphi because we have unit initialisation/finalisation
sections that can act as static constructors/destructors, and with
deterministic finalisation, we could simulate a static destructor in the
finalisation and clean up resources there on application closedown.

Now, bearing in mind that if I use the 'proper' Singleton pattern, I am
always accessing a static field through a static method, I can't see any
difference between using my own class of static methods to access the static
fields, and using the Singleton pattern.

My question is, do the instances pointed to by static fields ever get
garbage collected ?

I have always assumed that this happened as part of the tidy-up code that
got executed when the application quit.

Joanna

--
Joanna Carter
Consultant Software Engineer
Nov 17 '05 #1
9 4355
Hi,

Now, bearing in mind that if I use the 'proper' Singleton pattern, I am
always accessing a static field through a static method, I can't see any
difference between using my own class of static methods to access the
static
fields, and using the Singleton pattern.
Hi, It's not the same even as they looks much alike, if you use static
class you do not create an instance of the class , you cannot for example
pass around an instance of that class as a parameter to methods.

With a singleton you create an instance and after that there is no
difference between it and an instance of another class that is not
singleton. The only difference is that the singleton class has no public
construtor and you have 100% control of the construction process using the
static method/Property .
Also you could easily allow to destroy & recreate the instance at will:

// NOT THE BEST WAY TO IMPLEMENT a singleton
class singleton
{
static singleton theInstance = null;

public singleton GetIt
{
get
{
if ( theInstance == null )
theInstance = new singleton();
return theInstance;
}

//Remove the instance, when called again the property it will be
re-instanciated
public void Reset()
{
theInstance = null;
}

}

you cannot do that with a static class
My question is, do the instances pointed to by static fields ever get
garbage collected ?


All you have to do is assign it to null :

static DataSet ds = new DataSet();

void Clean()
{
ds = null;
}

Otherwise it will be kept until the AppDomain be active.

Cheers,

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

Nov 17 '05 #2
Hi,

Now, bearing in mind that if I use the 'proper' Singleton pattern, I am
always accessing a static field through a static method, I can't see any
difference between using my own class of static methods to access the
static
fields, and using the Singleton pattern.
Hi, It's not the same even as they looks much alike, if you use static
class you do not create an instance of the class , you cannot for example
pass around an instance of that class as a parameter to methods.

With a singleton you create an instance and after that there is no
difference between it and an instance of another class that is not
singleton. The only difference is that the singleton class has no public
construtor and you have 100% control of the construction process using the
static method/Property .
Also you could easily allow to destroy & recreate the instance at will:

// NOT THE BEST WAY TO IMPLEMENT a singleton
class singleton
{
static singleton theInstance = null;

public singleton GetIt
{
get
{
if ( theInstance == null )
theInstance = new singleton();
return theInstance;
}

//Remove the instance, when called again the property it will be
re-instanciated
public void Reset()
{
theInstance = null;
}

}

you cannot do that with a static class
My question is, do the instances pointed to by static fields ever get
garbage collected ?


All you have to do is assign it to null :

static DataSet ds = new DataSet();

void Clean()
{
ds = null;
}

Otherwise it will be kept until the AppDomain be active.

Cheers,

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

Nov 17 '05 #3
"Ignacio Machin ( .NET/ C# MVP )" <ignacio.mach in AT dot.state.fl.us > a
écrit dans le message de news: #o************* *@TK2MSFTNGP12. phx.gbl...
//Remove the instance, when called again the property it will be
re-instanciated
public void Reset()
{
theInstance = null;
}

}

you cannot do that with a static class
I would not want to do that with the static classes I have in mind, they
should be available at all times that the app is running.
My question is, do the instances pointed to by static fields ever get
garbage collected ?


All you have to do is assign it to null :

static DataSet ds = new DataSet();

void Clean()
{
ds = null;
}


In that case, I could just as well call a static method on my class to free
off the connections held by the static fields; the effect would be the same.
All I have to do is to call a 'finaliser' static method at the end of the
main() method of the app.
Otherwise it will be kept until the AppDomain be active.


If, by this, you mean when the application quits, then there should be no
problem.

My question was : If you have static fields that need Disposal of resources
and those fields are intended to last the entire run of the app, do I need
to explicitly finalise them or will the app closing do this for me ?

--
Joanna Carter
Consultant Software Engineer
Nov 17 '05 #4
"Ignacio Machin ( .NET/ C# MVP )" <ignacio.mach in AT dot.state.fl.us > a
écrit dans le message de news: #o************* *@TK2MSFTNGP12. phx.gbl...
//Remove the instance, when called again the property it will be
re-instanciated
public void Reset()
{
theInstance = null;
}

}

you cannot do that with a static class
I would not want to do that with the static classes I have in mind, they
should be available at all times that the app is running.
My question is, do the instances pointed to by static fields ever get
garbage collected ?


All you have to do is assign it to null :

static DataSet ds = new DataSet();

void Clean()
{
ds = null;
}


In that case, I could just as well call a static method on my class to free
off the connections held by the static fields; the effect would be the same.
All I have to do is to call a 'finaliser' static method at the end of the
main() method of the app.
Otherwise it will be kept until the AppDomain be active.


If, by this, you mean when the application quits, then there should be no
problem.

My question was : If you have static fields that need Disposal of resources
and those fields are intended to last the entire run of the app, do I need
to explicitly finalise them or will the app closing do this for me ?

--
Joanna Carter
Consultant Software Engineer
Nov 17 '05 #5
Joanna Carter (TeamB) <jo*****@nospam forme.com> wrote:

<snip>
Otherwise it will be kept until the AppDomain be active.
If, by this, you mean when the application quits, then there should be no
problem.


Usually that's the same thing, but not always. Chances are if you don't
know you're creating a new AppDomain, you're not :)
My question was : If you have static fields that need Disposal of resources
and those fields are intended to last the entire run of the app, do I need
to explicitly finalise them or will the app closing do this for me ?


Well, the finalizers will get run if the app goes down cleanly, *but*
they only get a few seconds to execute - so if there are lots of them
and one of them takes a while, the others won't happen.

Personally I'd always prefer to put some explicit shutdown code in.

--
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 #6
Joanna Carter (TeamB) <jo*****@nospam forme.com> wrote:

<snip>
Otherwise it will be kept until the AppDomain be active.
If, by this, you mean when the application quits, then there should be no
problem.


Usually that's the same thing, but not always. Chances are if you don't
know you're creating a new AppDomain, you're not :)
My question was : If you have static fields that need Disposal of resources
and those fields are intended to last the entire run of the app, do I need
to explicitly finalise them or will the app closing do this for me ?


Well, the finalizers will get run if the app goes down cleanly, *but*
they only get a few seconds to execute - so if there are lots of them
and one of them takes a while, the others won't happen.

Personally I'd always prefer to put some explicit shutdown code in.

--
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 #7
"Jon Skeet [C# MVP]" <sk***@pobox.co m> a écrit dans le message de news:
MP************* ***********@msn ews.microsoft.c om...
Well, the finalizers will get run if the app goes down cleanly, *but*
they only get a few seconds to execute - so if there are lots of them
and one of them takes a while, the others won't happen.

Personally I'd always prefer to put some explicit shutdown code in.


So, I would be best having something like the following :

static class ObjectStore
{
private ClassThatUsesRe source fred;
...
public static void Shutdown()
{
fred.Dispose();
fred = null;
}
}

....called from Main()

{
...
ObjectStore.Shu tdown(); // last line in main()
}

???

Joanna

--
Joanna Carter (TeamB)

Consultant Software Engineer
TeamBUG support for UK-BUG
TeamMM support for ModelMaker
Nov 17 '05 #8
Joanna Carter (TeamB) <jo*****@nospam forme.com> wrote:
Well, the finalizers will get run if the app goes down cleanly, *but*
they only get a few seconds to execute - so if there are lots of them
and one of them takes a while, the others won't happen.

Personally I'd always prefer to put some explicit shutdown code in.


So, I would be best having something like the following :

static class ObjectStore
{
private ClassThatUsesRe source fred;
...
public static void Shutdown()
{
fred.Dispose();
fred = null;
}
}

...called from Main()

{
...
ObjectStore.Shu tdown(); // last line in main()
}

???


Yup - something like that. Of course, if you can avoid doing it the
first place, that would be even better. (Keeping a resource for the
duration of an app is normally not a brilliant idea, especially if that
resource won't get automatically cleaned up if the app crashes hard.)

--
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 #9
In article <#o************ **@TK2MSFTNGP12 .phx.gbl>,
"Ignacio Machin \( .NET/ C# MVP \)" <ignacio.mach in AT
dot.state.fl.us > wrote:
class singleton
{
static singleton theInstance = null;

public singleton GetIt
{
get
{
if ( theInstance == null )
theInstance = new singleton();
return theInstance;
}
...
}


Should you not add to this class the constructor:

private singleton()
{
}

so as not to allow it to be instantiated outside the class?
Nov 17 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
3179
by: lawrence | last post by:
To call I would do something like: $headline = McSelectJustOneField::callDatastore("cbHeadline"); Is this the correct use of the static keyword, to implement a Singleton design?
3
3145
by: Dominik Rau | last post by:
Hi. I've got the following problem here: In my application, I use a lot of Singletons, that are implemented as described in Gamma et al. (shortened): //.h class Singleton{ public: static Singleton* the(); private: static Singleton* _instance;
17
51415
by: Tom | last post by:
This is not intuitivelly clear.
18
3310
by: Frank Rizzo | last post by:
Hello, I have a class with all static methods that is called by multiple threads. I was wondering what effect that has on the competing threads. Does Thread2 have to wait until Thread1 is done with the StaticClass.Method1 before it can use it? What if I removed static methods and made all the threads instantiate its own copy of the...
3
1576
by: mark.norgate | last post by:
Hello I'm writing an application in ASP.NET 1.1 and have come across a problem using static fields in my page classes. I have lots of controls on the page that all need to bind to the same datasource, so I thought I'd create a singleton in the base class that reads from the database and provides a DatasSet to all instances of the various...
7
2408
by: Brybot | last post by:
Apparently it is not possible for a static class to extend an abstract class? I was wondering how else I might be able to go about my problem here? I have a base class Parent which has a static method and an abstract method. public abstract class Parent { public static bool True()
4
2987
by: DBC User | last post by:
I have a class with bunch of static methods. I could regourp all the static methods into seperate 3 or 4 classes. I was thinking about using Singlton pattern for all these 4 classes so that it behaves like static still class. But my concern is, when going from static to singlton, I need to add one more line to make sure the class is...
7
1993
by: intrader | last post by:
I have the following small classes: //----------------code--------------- using System; using System.Collections.Generic; using System.Text; namespace ValidatorsLibrary { public class ValidatorBase {
6
4212
by: GroupReader | last post by:
In my app, I have two very similar static classes. After long thought, I've decided *yes - keep them static*. - Sometimes I will want to use Static Class A, and somtimes I will want to use Static Class B, depending on the situation. - The interfaces (are interfaces allowed on static classes?) are almost identical. What's the best way...
6
10344
by: =?Utf-8?B?R29yZG8=?= | last post by:
Hello everyone, I've been trying for some time now to move to C++/CLI, but I have several large legacy C++ static libraries I need to use. When I set up a simple solution with a C++/CLI Winforms app and a C++ native static library, they work well together _unless_ I have, it seems, any static variables defined in any function in the native...
0
7924
Oralloy
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. ...
0
8122
jinu1996
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...
0
7970
tracyyun
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...
0
6284
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5219
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...
0
3653
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2113
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1213
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
937
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.