473,796 Members | 2,473 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
13 3063
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.co m> wrote in message
news:MP******** *************** @msnews.microso ft.com...
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 #12
Ollie Riches <ol**********@p honeanalyser.ne t> 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.co m>
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(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 #14

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

Similar topics

1
2040
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
2500
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
2172
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
6351
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
2967
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
2854
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
18255
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
9680
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
9528
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,...
0
10456
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
10230
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...
1
10174
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,...
0
9052
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...
0
5575
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3731
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2926
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.