473,395 Members | 1,418 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,395 software developers and data experts.

Singleton Pattern and Collections

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 code looks like this:

public sealed class Reference
{
private static readonly Reference instance = new Reference();

// Make the default constructor private, so that nothing can directly
create it.
private Reference()
{
}

// public property that can only get the single instance of this class
public static Reference Data
{
get
{
return instance;
}
}
And then after that, but within the class, I add whatever properties I want.
This has served me very well.

But now I'd like to expand the use of the Singleton pattern to include
collections such as Users. My Users collection will be populated with a User
object, that itself will contain many properties such as "ID", "Name", etc.

I hit a roadblock though when I copied the above code to a new class I had
built for this purpose. The problem - I think - is that because the parent
class is sealed I can no longer access sub-classes like "User".

So I'm not sure how to proceed, other than removing the Singleton pattern.
This works but isn't really correct because now a developer could incorrectly
instantiate multiple versions when there really should be only one.

Any ideas how I could resolve this?

--
Robert W.
Vancouver, BC
www.mwtech.com

Nov 17 '05 #1
13 3025
Robert W. <Ro*****@discussions.microsoft.com> wrote:
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 code looks like this:
<snip>

That all seems to be correct.

And then after that, but within the class, I add whatever properties I want.
This has served me very well.

But now I'd like to expand the use of the Singleton pattern to include
collections such as Users. My Users collection will be populated with a User
object, that itself will contain many properties such as "ID", "Name", etc.

I hit a roadblock though when I copied the above code to a new class I had
built for this purpose. The problem - I think - is that because the parent
class is sealed I can no longer access sub-classes like "User".

So I'm not sure how to proceed, other than removing the Singleton pattern.
This works but isn't really correct because now a developer could incorrectly
instantiate multiple versions when there really should be only one.

Any ideas how I could resolve this?


I don't think I quite understand you. Are you saying there should only
be one collection of users? If so, create some class representing the
users, and make that a singleton. I don't see where class derivation
comes in...

You don't derive from a singleton class to create another singleton
class - singleton classes should always be sealed (and/or only have a
private constructor) as otherwise you end up with something which isn't
definitely a singleton.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #2
I think I see Robert's problem. Maybe.

Robert: you can't create a generic "singleton reference class" and then
inherit from it to get different kinds of singletons. I doesn't work
that way.

You have to implement the Singleton pattern separately for each class
that you want to be a Singleton. These classes _can_ inherit from a
common parent, if in real-world terms it makes sense to do so, but the
parent wouldn't be a Singleton... it would likely be abstract, or
designed so that only its child classes could instantiate it.

Was that what you were asking?

Nov 17 '05 #3
Jon, Bruce,

Thank you both for responding. All of your insight helped me. What I was
doing wrong was including nested classes - such as "Users", "User",
"Devices", and "Device" inside the parent class. Once I turned the parent
class into a sealed Singleton class then I could no longer access the nested
classes.

Seems so simple now but I was completely stumped earlier today.

My dilemma now is that for another complex class I had built a completely
generic XML export function (the built-in one never worked) and a fairly
generic XML import function. Unfortunately they don't appear to work when
the parent class is a Singleton one. But I'm going to investigate if a
little tweaking would resolve it.

If that doesn't work then I can just forego the Singleton-nature and only
instantiate the parent class once. True this wouldn't be correct for
circulating the library to others, but since I'm in control of it myself it
might suffice.

I think I'm at that point in my project now where while I want to do
everything perfectly and generically, I also have to get the damned thing
done! :-)

--
Robert W.
Vancouver, BC
www.mwtech.com

"Bruce Wood" wrote:
I think I see Robert's problem. Maybe.

Robert: you can't create a generic "singleton reference class" and then
inherit from it to get different kinds of singletons. I doesn't work
that way.

You have to implement the Singleton pattern separately for each class
that you want to be a Singleton. These classes _can_ inherit from a
common parent, if in real-world terms it makes sense to do so, but the
parent wouldn't be a Singleton... it would likely be abstract, or
designed so that only its child classes could instantiate it.

Was that what you were asking?

Nov 17 '05 #4
Robert W. <Ro*****@discussions.microsoft.com> wrote:
Thank you both for responding. All of your insight helped me. What I was
doing wrong was including nested classes - such as "Users", "User",
"Devices", and "Device" inside the parent class. Once I turned the parent
class into a sealed Singleton class then I could no longer access the nested
classes.


You should be able to. Note that nested classes aren't derived from the
containing class. There shouldn't be any problem there.

Personally I wouldn't recommend using nested classes terribly often -
they're good for classes which are *only* used by their containing
classes (so they can be basically invisible to everything else) but
other than that, I'd stick to "one class per file".

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


Robert W. wrote:
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 code looks like this:
That's a Singleton alright: a global variable holding an instance of a
class with only one instantiation. (As you may suspect, I'm not really
convinced singleton is a good design-pattern :)
But now I'd like to expand the use of the Singleton pattern to include
collections such as Users. My Users collection will be populated with a User
object, that itself will contain many properties such as "ID", "Name", etc.


Do you even *need* a UserCollection class? can't you use an ISet<User>
implementation? (which unfortunatly isn't available in .NET1.1 but can
be simply implemented using an IDictionary):

void f(ISet<User> users) {
foreach ( User u in users )
...;
}

Lets assume UserCollection have som functionality not in ISet<User>,
then and lets implement it:

public class UserCollection:
// you may implement ISet by composition or inheritance,
ISet<User>
{
public Add(User u) { ...something not in ISet implementation... }
... more things not in ISet implementation
}

now, I would just pass the UserCollection to operate on amongst functions:

void f(UserCollection users, ...) {
foreach ( User in users )
...
}

Why do you need to guarantee that only one instance of a UserCollection
ever exists? What value does it add to your program? what value does it
remove? (remember, it makes UserCollection a global variable and
prevents others from using the collection to represent Users).

If you believe passing the UserCollection around is too bothersome, you
can add:

public static UserCollection Global = new UserCollection();

to class UserCollection. Now UserCollection.Global is effectively a
global variable (which is like a singleton, without guarantee that the
class is only intantiated once). This makes using code look like:

void f(...) {
foreach ( User in UserCollection.Global )
...
}

I have, (almost) never seen anywhere where the "only one instance of a
class" property yields value to a programs. the "global variable"
property is used often though... and people are even pround of it
because Singleton is a design pattern -- even though they haughtily
snorts at global variables as a rule!

--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 17 '05 #6
Robert,

This site has a list of common design patterns and examples in .Net

http://www.dofactory.com/Patterns/Patterns.aspx

HTH

Ollie Riches

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Robert W. <Ro*****@discussions.microsoft.com> wrote:
Thank you both for responding. All of your insight helped me. What I
was
doing wrong was including nested classes - such as "Users", "User",
"Devices", and "Device" inside the parent class. Once I turned the
parent
class into a sealed Singleton class then I could no longer access the
nested
classes.


You should be able to. Note that nested classes aren't derived from the
containing class. There shouldn't be any problem there.

Personally I wouldn't recommend using nested classes terribly often -
they're good for classes which are *only* used by their containing
classes (so they can be basically invisible to everything else) but
other than that, I'd stick to "one class per file".

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

Nov 17 '05 #7

"Helge Jensen" <he**********@slog.dk> wrote in message
news:O5**************@TK2MSFTNGP10.phx.gbl...


Robert W. wrote:
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 code looks like
this:


That's a Singleton alright: a global variable holding an instance of a
class with only one instantiation. (As you may suspect, I'm not really
convinced singleton is a good design-pattern :)


What would you use instead ? If you wanted to be sure that there is only one
instance of a certain class ?

--
Best regards C.T.O. Søren Reinke
www.Xray-Mag.com/ - Your free diving magazin on the net. Download it in PDF
Aug-sept issue of X-RAY Magazine is ready to download:
EGYPT Finding Yolanda Wreck, Celebrate the Seas 2005
Nov 17 '05 #8
In message <MP************************@msnews.microsoft.com >, Jon Skeet
<?@pobox.com.invalid> writes
Personally I wouldn't recommend using nested classes terribly often -
they're good for classes which are *only* used by their containing
classes (so they can be basically invisible to everything else) but
other than that, I'd stick to "one class per file".


Or which are only exposed via an interface visible elsewhere;
enumerators, for example.

--
Steve Walker
Nov 17 '05 #9
Ollie Riches <ol**********@phoneanalyser.net> wrote:
Robert,

This site has a list of common design patterns and examples in .Net

http://www.dofactory.com/Patterns/Patterns.aspx


Unfortunately, the simple example given isn't threadsafe, and the more
complicated one uses double-checked locking (which doesn't work without
using a volatile field) and a Mutex rather than a Monitor (which is
needlessly expensive).

See http://www.pobox.com/~skeet/csharp/singleton.html for better
implementations.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #10
Helge (and others),

You raise some interesting points. Let me go back to basics [of what I'm
trying to accomplish]. I have some data that I call "SysInfo" - User Info,
Supported Device (my app works with PPC apps), and Global Options. I also
have some data that I call "RefData" - Countries, Cities, Area Codes and
other such things.

In both cases, I need this data to be available to every module. Yes, I
suppose I could just pass these data objects around but I think that'll get
quite cumbersome.

I originally implemented the Singleton pattern because I thought (and I
think I had read) that it was the right solution for this kind of data:
- Global to everything
- Instantiated only once

While it's true that if I'm the only developer then I can just instantiate a
regular (non-Singleton) object and know not to instantiate it again, I
thought that Singleton was better if multiple developers got involved to
ensure that everyone was forced not to have multiple copies of what should be
just one set of data.

I very much welcome back any and all further feedback to this.

--
Robert W.
Vancouver, BC
www.mwtech.com

Nov 17 '05 #11
Thanks for tht Jon, Shot down in flames again :)

Ollie Riches

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP***********************@msnews.microsoft.co m...
Ollie Riches <ol**********@phoneanalyser.net> wrote:
Robert,

This site has a list of common design patterns and examples in .Net

http://www.dofactory.com/Patterns/Patterns.aspx


Unfortunately, the simple example given isn't threadsafe, and the more
complicated one uses double-checked locking (which doesn't work without
using a volatile field) and a Mutex rather than a Monitor (which is
needlessly expensive).

See http://www.pobox.com/~skeet/csharp/singleton.html for better
implementations.

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

Nov 17 '05 #12
Ollie Riches <ol**********@phoneanalyser.net> wrote:
Thanks for tht Jon, Shot down in flames again :)


Oh, I don't think that was very flamy. You should see me get going when
people claim that C# passes objects by references by default ;

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

Can I ask you a quick follow-up to something you said?

Your Singleton alternative used this syntax:
public static UserCollection Global = new UserCollection();

But then that means that everytime I want to reference anything I have to
prefix it with "UserCollection.Global." This just seems so redundant to me.

Is there a way to instantiate a global variable so that I could just
reference the various properties with this prefix: "UserCollection." ?

--
Robert W.
Vancouver, BC
www.mwtech.com

"Helge Jensen" wrote:


Robert W. wrote:
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 code looks like this:


That's a Singleton alright: a global variable holding an instance of a
class with only one instantiation. (As you may suspect, I'm not really
convinced singleton is a good design-pattern :)
But now I'd like to expand the use of the Singleton pattern to include
collections such as Users. My Users collection will be populated with a User
object, that itself will contain many properties such as "ID", "Name", etc.


Do you even *need* a UserCollection class? can't you use an ISet<User>
implementation? (which unfortunatly isn't available in .NET1.1 but can
be simply implemented using an IDictionary):

void f(ISet<User> users) {
foreach ( User u in users )
...;
}

Lets assume UserCollection have som functionality not in ISet<User>,
then and lets implement it:

public class UserCollection:
// you may implement ISet by composition or inheritance,
ISet<User>
{
public Add(User u) { ...something not in ISet implementation... }
... more things not in ISet implementation
}

now, I would just pass the UserCollection to operate on amongst functions:

void f(UserCollection users, ...) {
foreach ( User in users )
...
}

Why do you need to guarantee that only one instance of a UserCollection
ever exists? What value does it add to your program? what value does it
remove? (remember, it makes UserCollection a global variable and
prevents others from using the collection to represent Users).

If you believe passing the UserCollection around is too bothersome, you
can add:

public static UserCollection Global = new UserCollection();

to class UserCollection. Now UserCollection.Global is effectively a
global variable (which is like a singleton, without guarantee that the
class is only intantiated once). This makes using code look like:

void f(...) {
foreach ( User in UserCollection.Global )
...
}

I have, (almost) never seen anywhere where the "only one instance of a
class" property yields value to a programs. the "global variable"
property is used often though... and people are even pround of it
because Singleton is a design pattern -- even though they haughtily
snorts at global variables as a rule!

--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-

Nov 17 '05 #14

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

Similar topics

1
by: Richard A. DeVenezia | last post by:
foo() generates elements with event handlers that invoke foo function properties. Is this an abhorrent or misthought pattern ? It allows just the one occurence of identifier /foo/ to be changed...
3
by: Alicia Roberts | last post by:
Hello everyone, I have been researching the Singleton Pattern. Since the singleton pattern uses a private constructor which in turn reduces extendability, if you make the Singleton Polymorphic...
11
by: Daniel Billingsley | last post by:
Let's say I'm writing a business app and I want there to be only one instance of the Customer object for each particular customer (representing a database record) being edited. Would it be...
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: Kevin Newman | last post by:
I have been playing around with a couple of ways to add inheritance to a JavaScript singleton pattern. As far as I'm aware, using an anonymous constructor to create a singleton does not allow any...
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: dischdennis | last post by:
Hello List, I would like to make a singleton class in python 2.4.3, I found this pattern in the web: class Singleton: __single = None def __init__( self ): if Singleton.__single: raise...
13
by: David | last post by:
Hi all, I have a singleton ienumerable that collects data from a database. I have listed the code below. It has the usual methods of current, move and reset. I need to go to a certain position...
3
weaknessforcats
by: weaknessforcats | last post by:
Design Pattern: The Singleton Overview Use the Singleton Design Pattern when you want to have only one instance of a class. This single instance must have a single global point of access. That...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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...

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.