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

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 1126
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.GetMeWhatINeed(...);

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*******@canada.comwrote in message
news:11**********************@p79g2000cwp.googlegr oups.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.GetMeWhatINeed(...);

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
"ServerClient" 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*******@canada.comwrote in message
news:11**********************@p79g2000cwp.googlegr oups.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.GetMeWhatINeed(...);

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.
--
"ThunderMusic" <No*************************@NoSpAm.comwrote in message
news:OJ**************@TK2MSFTNGP05.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
"ThunderMusic" <No*************************@NoSpAm.comwrote in message
news:ur**************@TK2MSFTNGP02.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*******@hotmail.nospam.comwrote 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.
--
"ThunderMusic" <No*************************@NoSpAm.comwrote in message
news:OJ**************@TK2MSFTNGP05.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
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...
1
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 ...
3
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
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...
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...
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...
6
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...
3
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() {...
2
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"...
4
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
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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?
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:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.