473,406 Members | 2,698 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Jon Skeet's singleton pattern - questions

Hello,

I am still fairly new to CSharp and am trying to implement a singleton
pattern. I found Jon Skeet's excellent page
(http://www.yoda.arachsys.com/csharp/singleton.html), but am struggling a
little to understand it.

The 4th example seems to be the preferred:

public sealed class Singleton
{

static readonly Singleton instance=new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
// this is a private static constructor right?
}
Singleton()
{
// this is a private instance constructor?

}
public static Singleton GetInstance()
{
return instance;
}
}

OK, so if I create a new instance of singleton, like this:
Singleton MyInstance = new Singleton;
there is no public constructor, so nothing will happen?

But if I call Singleton.GetInstance, a new incidence of singleton will be
created (if required ) and returned due to the readonly variable? Could I
declare instance as public static readonly and get rid of GetInstance?

I understand from the body of that page that the private static
constructor is necessary to make the beforefieldinit bookkeeping work
out, but why is the other constructor necessary, since they are both
private? Would there be a scenario, where different code would be
required in either?

Thanks for any illumination.

Marc Pelletier
Nov 15 '05 #1
7 2282
Marc Pelletier <no******@please.com> wrote:
I am still fairly new to CSharp and am trying to implement a singleton
pattern. I found Jon Skeet's excellent page
(http://www.yoda.arachsys.com/csharp/singleton.html), but am struggling a
little to understand it.

The 4th example seems to be the preferred:
It's certainly preferred by me :)
OK, so if I create a new instance of singleton, like this:
Singleton MyInstance = new Singleton;
there is no public constructor, so nothing will happen?
No - a compiler error will happen. You just can't do it.
But if I call Singleton.GetInstance, a new incidence of singleton will be
created (if required ) and returned due to the readonly variable? Could I
declare instance as public static readonly and get rid of GetInstance?
Yes, although that would limit you in terms of future changes to (say)
the fifth pattern.
I understand from the body of that page that the private static
constructor is necessary to make the beforefieldinit bookkeeping work
out, but why is the other constructor necessary, since they are both
private? Would there be a scenario, where different code would be
required in either?


The private constructor is required solely in order to stop the
compiler from generating a default constructor, which would be public.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #2
Jon Skeet [C# MVP] <sk***@pobox.com> wrote in
news:MP************************@msnews.microsoft.c om:
OK, so if I create a new instance of singleton, like this:
Singleton MyInstance = new Singleton;
there is no public constructor, so nothing will happen?


No - a compiler error will happen. You just can't do it.


Right, should have realized that.
But if I call Singleton.GetInstance, a new incidence of singleton
will be created (if required ) and returned due to the readonly
variable? Could I declare instance as public static readonly and get
rid of GetInstance?


Yes, although that would limit you in terms of future changes to (say)
the fifth pattern.

Okay, right, same reason we use properties. I thought so.
I understand from the body of that page that the private static
constructor is necessary to make the beforefieldinit bookkeeping work
out, but why is the other constructor necessary, since they are both
private? Would there be a scenario, where different code would be
required in either?


The private constructor is required solely in order to stop the
compiler from generating a default constructor, which would be public.


Okay, more bookkeeping. But when the instance variable is created,
which constructor will be called? Where should my constructor code actually
go?

Thanks for all of this, and especially the web page.

Marc Pelletier

Nov 15 '05 #3
Marc Pelletier <no******@please.com> wrote:
The private constructor is required solely in order to stop the
compiler from generating a default constructor, which would be public.
Okay, more bookkeeping. But when the instance variable is created,
which constructor will be called? Where should my constructor code actually
go?


There *is* only one constructor - the private one. So that's what will
be called when the instance is created, and that's where you should put
your real constructor code.
Thanks for all of this, and especially the web page.


My pleasure - glad it's useful.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #4
What if you need to pass in parameters in to the constructor

Would the 2nd version work? i.e

public sealed class Singleto

static Singleton instance=null
static readonly object padlock = new object()

string server
string db

Singleton(

public static Singleton GetInstance(string db, string server

lock (padlock

if (instance==null

this.server = server
this.db = db
instance = new Singleton(db, server)
return instance

Further more, would the thread-safe instance still work in the Get instance method was overloaded

Nov 15 '05 #5
markeboy <an*******@discussions.microsoft.com> wrote:
What if you need to pass in parameters in to the constructor.


Then the first thing you need to consider is what happens if the second
time you call GetInstance, you pass in different parameters. It looks
like what you're really after there is the Factory pattern (with
caching) rather than the Singleton pattern. And yes, so long as you
explicitly lock, it will then work (typically with a map from
parameters to created objects).

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #6
bob
Hello,
in the past when I've done this sort of thing (albeit in Smalltalk)
I've simply made the class the singleton and made all methods static.
This seems to remove all problems involving thread safty, but what
problems does it leave?

please explain?

thanks,

bob
Nov 15 '05 #7
bob <bo**********@hotmail.com> wrote:
in the past when I've done this sort of thing (albeit in Smalltalk)
I've simply made the class the singleton and made all methods static.
This seems to remove all problems involving thread safty, but what
problems does it leave?


If you're going to make all the methods static, there's no point in
making it a singleton in the first place, as you never need to create
*any* instances. The idea of a singleton is that you can use it as an
instance. This means it can implement interfaces usefully, and also you
can decide later to make it *not* a singleton with far less hassle.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #8

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

Similar topics

13
by: Stampede | last post by:
I woundered if the following would be possible: I want to create an abstract Singleton class, which implements the singleton behaviour with the limitation, that the unique object will not be...
15
by: Mountain Bikn' Guy | last post by:
Is the second version shown below better? I couldn't locate enough info about in order to tell. 1.. My commonly used singleton pattern implementation looks like this (it was inspired by Eric...
13
by: William Stacey | last post by:
FYI. /// <summary> /// Author: William Stacey /// Fast and simple way to implement a singleton pattern without resorting /// to nested classes or other static vodo. Can also be easily converted...
21
by: Sharon | last post by:
I wish to build a framework for our developers that will include a singleton pattern. But it can not be a base class because it has a private constructor and therefore can be inherit. I thought...
2
by: Jonathan Rea | last post by:
Hey, I currently have the following code : public sealed class FFManager { // Singleton pattern - single initialisation of FFManager for the application private static readonly FFManager...
13
by: Robert W. | last post by:
At the beginning of my C# days (about 6 months ago) I learned about the Singleton pattern and implemented for Reference data, such as the kind that appears in an Options dialog box. My Singleton...
7
by: INeedADip | last post by:
I want to get some feedback so don't hold back. I have a webservice that is responsible for Formatting a ton of information that is then queried by other applications (agents) that utilize it...
3
by: koredump | last post by:
I have inherited a Business Object architecture that makes heavy use of the Singleton design patter. For example the data access layer class is implemented as a static Singleton "object", there...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
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,...
0
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...
0
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...
0
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...
0
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...
0
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,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.