473,721 Members | 2,254 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Singleton problem

Hi,
I have a problem regarding singletons in C#. What I would like to do is the
following

ClassA is a singleton
ClassB inherits from ClassA and is also a Singleton
there cannot and instance of ClassA and an instance of ClassB, there must be
only one of one or the other...

Is there a way to do it? or it's simply not possible?

I tried to put the m_instance member variable protected, so the inherited
classes can see it, but the problem is when I have the method Instance(), it
returns the instance of ClassA, not the instance of classB, and if I
override it, I can't change it's return type... Is there a way to shadow the
original method which returns ClassA to replace it with a method that
returns ClassB?

Thanks

ThunderMusic
Jul 31 '06 #1
7 1427
ThunderMusic,

To do that ClassA must not be marked as sealed or have a private
constructor. That pretty much makes it impossible to guarentee that
there will be one and only one of ClassA or any of its subclasses.

Have you looked into using one of the factory design patterns? Maybe
one would be better suited for your problem.

Brian

ThunderMusic wrote:
Hi,
I have a problem regarding singletons in C#. What I would like to do is the
following

ClassA is a singleton
ClassB inherits from ClassA and is also a Singleton
there cannot and instance of ClassA and an instance of ClassB, there must be
only one of one or the other...

Is there a way to do it? or it's simply not possible?

I tried to put the m_instance member variable protected, so the inherited
classes can see it, but the problem is when I have the method Instance(), it
returns the instance of ClassA, not the instance of classB, and if I
override it, I can't change it's return type... Is there a way to shadow the
original method which returns ClassA to replace it with a method that
returns ClassB?

Thanks

ThunderMusic
Jul 31 '06 #2

ThunderMusic wrote:
Hi,
I have a problem regarding singletons in C#. What I would like to do is the
following

ClassA is a singleton
ClassB inherits from ClassA and is also a Singleton
there cannot and instance of ClassA and an instance of ClassB, there must be
only one of one or the other...

Is there a way to do it? or it's simply not possible?
I would move toward a type of Factory pattern, where you have a Factory
method that creates either an A or a B on the first request (depending
upon arguments passed) and then from thereon in returns the same
instance over and over again.

I see what you're trying to do: really you have two factory "methods":
A.Instance and B.Instance, and you want the first one called to
allocate the instance and then from then on both return the same thing:
the originally allocated instance. However, don't you think that
callers will find this confusing? It looks like two singletons, but
they're not really independent singletons.

I would find it easier to understand this:

A whatever = B.GetMeWhatINee d(...);

where "whatever" ends up being either an A or a B, and then always
returns the same object after that. Easier to program, easier to
remember what's going on, IMHO.

Jul 31 '06 #3
ok, here's the real deal... I have a Client and a Server Class and the
Server is also a Client of it's own network and does exactly all the same
things that Client does plus some other things... But I don't want the
programmer to create a Client and a Server, I just want him to create one or
the other, but not both... because creating both would end up doing twice
the same job (the Client's job).

You know what I mean?

thanks for your answers...

ThunderMusic

"Bruce Wood" <br*******@cana da.comwrote in message
news:11******** **************@ p79g2000cwp.goo glegroups.com.. .
>
ThunderMusic wrote:
>Hi,
I have a problem regarding singletons in C#. What I would like to do is
the
following

ClassA is a singleton
ClassB inherits from ClassA and is also a Singleton
there cannot and instance of ClassA and an instance of ClassB, there must
be
only one of one or the other...

Is there a way to do it? or it's simply not possible?

I would move toward a type of Factory pattern, where you have a Factory
method that creates either an A or a B on the first request (depending
upon arguments passed) and then from thereon in returns the same
instance over and over again.

I see what you're trying to do: really you have two factory "methods":
A.Instance and B.Instance, and you want the first one called to
allocate the instance and then from then on both return the same thing:
the originally allocated instance. However, don't you think that
callers will find this confusing? It looks like two singletons, but
they're not really independent singletons.

I would find it easier to understand this:

A whatever = B.GetMeWhatINee d(...);

where "whatever" ends up being either an A or a B, and then always
returns the same object after that. Easier to program, easier to
remember what's going on, IMHO.

Jul 31 '06 #4
I don't fully understand why you would do this. Anyway, you could do
the following:

class MyBase {
private static bool Created = false;

public override string ToString() {
return "MyBase";
}

public MyBase() {
if(Created) {
throw new Exception("I can't be created twice!");
}
Created = true;
}
}

So if this class is created, or any class that inherits it, another one
being created will show an exception.

The only problem is, if you dereference the object, the static boolean
still lingers, so you could write a Dispose method that changed Created
back to false, but the programmer would have to call it before
dereferencing the object, because Garbage Collection happens when it
wants to, and there are no guarantees when that wil happen.

Or you could just call one class "Client" and the other one
"ServerClie nt" which will make it obvious to the programmer that only
one is needed.

Buena Suerte!!
Vincent.

ThunderMusic wrote:
ok, here's the real deal... I have a Client and a Server Class and the
Server is also a Client of it's own network and does exactly all the same
things that Client does plus some other things... But I don't want the
programmer to create a Client and a Server, I just want him to create one or
the other, but not both... because creating both would end up doing twice
the same job (the Client's job).

You know what I mean?

thanks for your answers...

ThunderMusic

"Bruce Wood" <br*******@cana da.comwrote in message
news:11******** **************@ p79g2000cwp.goo glegroups.com.. .

ThunderMusic wrote:
Hi,
I have a problem regarding singletons in C#. What I would like to do is
the
following

ClassA is a singleton
ClassB inherits from ClassA and is also a Singleton
there cannot and instance of ClassA and an instance of ClassB, there must
be
only one of one or the other...

Is there a way to do it? or it's simply not possible?
I would move toward a type of Factory pattern, where you have a Factory
method that creates either an A or a B on the first request (depending
upon arguments passed) and then from thereon in returns the same
instance over and over again.

I see what you're trying to do: really you have two factory "methods":
A.Instance and B.Instance, and you want the first one called to
allocate the instance and then from then on both return the same thing:
the originally allocated instance. However, don't you think that
callers will find this confusing? It looks like two singletons, but
they're not really independent singletons.

I would find it easier to understand this:

A whatever = B.GetMeWhatINee d(...);

where "whatever" ends up being either an A or a B, and then always
returns the same object after that. Easier to program, easier to
remember what's going on, IMHO.
Aug 1 '06 #5
Singleton is an often abused pattern that should be used only to protect a
resource that requires one and only one access point (like an HTTP port or
an open file). Be careful.

Normally, if you have the need to create two alternate singletons, you have
some variation in the resource that you are trying to hide from the calling
code. I can think of two designs that will do this for you.

A) Singleton Strategy
You have a singleton object that presents a consistent interface to the
calling code. The singleton constructor, however, is used to create one or
another objects that inherit from a strategy interface. In effect, the
singleton constructor is, or calls, a strategy factory method to create a
contained object. The singleton then uses the strategy object to perform
the key varying parts of its work.

Singleton <>--------- IStrat
A
|
+------+-------+
| |
ConcStrat1 ConcStrat2
B) The singleton itself stores a child object (this is as close to what you
are trying to get at as I can figure).

This means that the base class is (a) concrete, and (b) stores a member of
its own type. Two child classes inherit from the concrete base. The base
constructor does nothing. The child constructors do nothing. You set state
on the concrete base class' other properties to help it to drive the factory
logic. When you call the concrete base class' GetReference method the first
time, it will use the other properties to decide which child object to
create and store locally. The type of the returned object is always the
base type, so you'd better not need a variation in interface for the child
objects.

Personally, I like option A better. It is cleaner and easier to maintain.

Good luck.
--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
--
"ThunderMus ic" <No************ *************@N oSpAm.comwrote in message
news:OJ******** ******@TK2MSFTN GP05.phx.gbl...
Hi,
I have a problem regarding singletons in C#. What I would like to do is
the following

ClassA is a singleton
ClassB inherits from ClassA and is also a Singleton
there cannot and instance of ClassA and an instance of ClassB, there must
be only one of one or the other...

Is there a way to do it? or it's simply not possible?

I tried to put the m_instance member variable protected, so the inherited
classes can see it, but the problem is when I have the method Instance(),
it returns the instance of ClassA, not the instance of classB, and if I
override it, I can't change it's return type... Is there a way to shadow
the original method which returns ClassA to replace it with a method that
returns ClassB?

Thanks

ThunderMusic

Aug 1 '06 #6
"ThunderMus ic" <No************ *************@N oSpAm.comwrote in message
news:ur******** ******@TK2MSFTN GP02.phx.gbl...
ok, here's the real deal... I have a Client and a Server Class and the
Server is also a Client of it's own network and does exactly all the same
things that Client does plus some other things... But I don't want the
programmer to create a Client and a Server, I just want him to create one
or the other, but not both... because creating both would end up doing
twice the same job (the Client's job).

You know what I mean?

thanks for your answers...

ThunderMusic
With all due respect, ThunderMusic, your /constraint/ may not be necessary.
Simply provide a factory method that will create the ONE object that the
client needs and be done with it. If the client is dumb enough to create
both a client and a server object, let them. Who knows... perhaps someday
the requirements will change and a new requirement will come along where the
calling code *needs* to create five clients and two servers... and your code
will break.

As long as the creation of a server object doesn't PREVENT a client object
from working, let the calling code use what they need.

--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
--
Aug 1 '06 #7
thanks a lot, I'll look into it and see if it fits the needs... I think it
will...

"Nick Malik [Microsoft]" <ni*******@hotm ail.nospam.comw rote in message
news:VK******** *************** *******@comcast .com...
Singleton is an often abused pattern that should be used only to protect a
resource that requires one and only one access point (like an HTTP port or
an open file). Be careful.

Normally, if you have the need to create two alternate singletons, you
have some variation in the resource that you are trying to hide from the
calling code. I can think of two designs that will do this for you.

A) Singleton Strategy
You have a singleton object that presents a consistent interface to the
calling code. The singleton constructor, however, is used to create one
or another objects that inherit from a strategy interface. In effect, the
singleton constructor is, or calls, a strategy factory method to create a
contained object. The singleton then uses the strategy object to perform
the key varying parts of its work.

Singleton <>--------- IStrat
A
|
+------+-------+
| |
ConcStrat1 ConcStrat2
B) The singleton itself stores a child object (this is as close to what
you are trying to get at as I can figure).

This means that the base class is (a) concrete, and (b) stores a member of
its own type. Two child classes inherit from the concrete base. The base
constructor does nothing. The child constructors do nothing. You set
state on the concrete base class' other properties to help it to drive the
factory logic. When you call the concrete base class' GetReference method
the first time, it will use the other properties to decide which child
object to create and store locally. The type of the returned object is
always the base type, so you'd better not need a variation in interface
for the child objects.

Personally, I like option A better. It is cleaner and easier to maintain.

Good luck.
--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
--
"ThunderMus ic" <No************ *************@N oSpAm.comwrote in message
news:OJ******** ******@TK2MSFTN GP05.phx.gbl...
>Hi,
I have a problem regarding singletons in C#. What I would like to do is
the following

ClassA is a singleton
ClassB inherits from ClassA and is also a Singleton
there cannot and instance of ClassA and an instance of ClassB, there must
be only one of one or the other...

Is there a way to do it? or it's simply not possible?

I tried to put the m_instance member variable protected, so the inherited
classes can see it, but the problem is when I have the method Instance(),
it returns the instance of ClassA, not the instance of classB, and if I
override it, I can't change it's return type... Is there a way to shadow
the original method which returns ClassA to replace it with a method that
returns ClassB?

Thanks

ThunderMusic


Aug 1 '06 #8

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

Similar topics

16
6732
by: cppaddict | last post by:
Hi, In this tutorial on singleton class in C++ (http://gethelp.devx.com/techtips/cpp_pro/10min/10min0200.asp) the author gives two implementations of a simple singleton class, claiming that only the first is safe for multi-threaded appliactions. I want to know why this so. The class is as follows:
1
2451
by: Jim Strathmeyer | last post by:
So I'm trying to implement a singleton template class, but I'm getting a confusing 'undefined reference' when it tries to link. Here's the code and g++'s output. Any help? // singleton.h template <class T> class Singleton : public T { public: static T * Instance();
3
3924
by: Harry | last post by:
Hi ppl I have a doubt on singleton class. I am writing a program below class singleton { private: singleton(){}; public: //way 1
7
3616
by: Stephen Brown | last post by:
I have some strange behavior on my web server that seems to point to garbage collection. I have a singleton that tracks web activity on my web site. The singleton works great, except that it restarts periodically. The web services have not been restarted and the error log shows no problems. It is the same problem on 2 different servers, but is worse on the most used server. On the most used server, it gets restarted 5 to 10 times a day...
21
2461
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...
3
2964
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
6
3192
by: toton | last post by:
Hi, If I have a singleton class based on dynamic initialization (with new ) , is it considered a memory leak? Anything in C++ standard says about it ? And little off - topic question , If the singleton is initialized as a static variable , it seems there is some threading issue . Is it the issue during singleton initialization only , or during the access also? If the singleton is per thread basis (then no more singleton though ), and...
3
435
by: wizwx | last post by:
There are two typical implementations of a singleton. The first one is to use a static pointer class Singleton { static Singleton * pSingleton; public: Singleton * instance() { if(pSingleton==NULL) pSingleton = new Singleton; return pSingleton; }
2
1585
by: Bob Johnson | last post by:
Just wondering the extent to which some of you are implementing classes as Singletons. I'm working on a brand new project and, early on, identified some obvious candidates. By "obvoius candidates" I mean classes for which terrible problems would clearly arise if more than one instance were to exist. But as I'm getting into the design of this new solution, I'm realizing that a large percentage of the classes _could be_ implemented as...
4
2825
by: John Doe | last post by:
Hi, I have a singleton class defined like this : class UIManager : public CSingleton<UIManager>, public CObject { protected: DECLARE_DYNAMIC(UIManager) friend class CSingleton<UIManager>;
0
9367
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
9215
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
9131
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
9064
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
8007
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
6669
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
5981
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
4484
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3189
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

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.