473,785 Members | 2,412 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 3062
Robert W. <Ro*****@discus sions.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.co m>
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*****@discus sions.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.co m>
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(UserCollectio n 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.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Robert W. <Ro*****@discus sions.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.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 17 '05 #7

"Helge Jensen" <he**********@s log.dk> wrote in message
news:O5******** ******@TK2MSFTN GP10.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************ ************@ms news.microsoft. com>, Jon Skeet
<?@pobox.com.in valid> 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**********@p honeanalyser.ne t> 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.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #10

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

Similar topics

1
2038
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 to /whatever/ when need arises and everything should still work. function foo () { var callee = arguments.callee
3
2499
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 what sort of problems/issues should be considered? Also, I see that a singleton needs to be set up with certain data such as file name, database URL etc. What issues are involved in this, and how would you do this? If someone knows about the...
11
2171
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 possible to extend the Singleton pattern to handle this? Assuming that my Customer class follows the Singleton pattern (particularly Skeet's 4th version) I'm thinking if I add private static SomeCollectionType customers;
21
2469
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 maybe a Template can be use for that, but C# does not support Templates (will be C# generics in mid 2005). Does anyone have a solution on how the singleton pattern can be written, in C#, as a framework/ infrastructure class, so users can use this...
2
6348
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 kind of inheritance: singletonObj = new function() { this.prop = true; } Here are two ways to create a singleton with inheritance:
7
5708
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 (the info). All this "formatting" and logic I am talking about needs to be done in a centralized place and accessed by the agents. That is why we chose to go with a web service. Now...all this formatting needs to be done and held in memory so...
3
2965
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 Singleton.__single
13
2853
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 or set filters or many other things and I don't know how to do this. I have just learned singleton AND ienumerable, so miraculously got this to work so far. I could do with a bit of help to go further with it. If need by, I may have to change the...
3
18253
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 is, regardless of where the object is hidden, everyone needs access to it. The global point of access is the object's Instance() method. Individual users need to be prevented from creating their own instances of the Singleton.
0
9645
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10341
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10155
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9954
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8979
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7502
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6741
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();...
0
5513
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2881
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.