473,807 Members | 2,842 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can Singleton Instances Clash?

hi,

I have a singleton Evaluation class that I'm calling repeatedly in one
sequence. would someone plz have a look at the code below and tell me
if one instance of the singleton can ever "clash" with another?

I'm asking because I'm getting unexpected results. I've looked for the
problem the past several days and can't attribute the anomalies to
logic errors.

the Evaluate function uses private vectors and other internal class
members to return an int value corresponding to poker hand strength.

void Game::RunShowdo wn()
{
deque<Player> showDownPlayers ;

for(posPlayer = players.begin() ; posPlayer != players.end();
++posPlayer)
{
if((*posPlayer) .GetActive()) showDownPlayers .push_back(*pos Player);
}

ShowChipsStatus ();
ShowRiver();

for(posPlayer = showDownPlayers .begin(); posPlayer !=
showDownPlayers .end(); ++posPlayer)
{
cout << "\n " << (*posPlayer).Ge tLastName() << "'s hand:\n\n\n";
(*posPlayer).Ge tHand().Peek();
}

Player winner = showDownPlayers .front();

for(posPlayer = showDownPlayers .begin() + 1; posPlayer !=
showDownPlayers .end(); ++posPlayer)
{
if(Evaluation:: Instance().Eval uate(ReturnComm unityCards(),
(*posPlayer).Ge tHand()) >
Evaluation::Ins tance().Evaluat e(ReturnCommuni tyCards(),
winner.GetHand( ))) winner = (*posPlayer);
else if(Evaluation:: Instance().Eval uate(ReturnComm unityCards(),
(*posPlayer).Ge tHand()) ==
Evaluation::Ins tance().Evaluat e(ReturnCommuni tyCards(),
winner.GetHand( )))
{
if((*posPlayer) .GetHand().GetT opCard().GetVal ue() >
winner.GetHand( ).GetTopCard(). GetValue())
winner = (*posPlayer);
else if((*posPlayer) .GetHand().GetT opCard().GetVal ue() ==
winner.GetHand( ).GetTopCard(). GetValue())
{
if((*posPlayer) .GetHand().GetL owPairValue() >
winner.GetHand( ).GetLowPairVal ue())
winner = (*posPlayer);
else if((*posPlayer) .GetHand().GetL owPairValue() ==
winner.GetHand( ).GetLowPairVal ue())
{
if((*posPlayer) .GetHand().GetK icker().GetValu e() >
winner.GetHand( ).GetKicker().G etValue())
winner = (*posPlayer);
}
}
}

PayWinner(winne r);
}

Dec 7 '05 #1
10 1484
A_*********@hot mail.com wrote:
hi,

I have a singleton Evaluation class that I'm calling repeatedly in one
sequence. would someone plz have a look at the code below and tell me
if one instance of the singleton can ever "clash" with another?

I'm asking because I'm getting unexpected results. I've looked for the
problem the past several days and can't attribute the anomalies to
logic errors.

the Evaluate function uses private vectors and other internal class
members to return an int value corresponding to poker hand strength.

void Game::RunShowdo wn()
{
deque<Player> showDownPlayers ;

for(posPlayer = players.begin() ; posPlayer != players.end();
++posPlayer)
{
if((*posPlayer) .GetActive()) showDownPlayers .push_back(*pos Player);
}

ShowChipsStatus ();
ShowRiver();

for(posPlayer = showDownPlayers .begin(); posPlayer !=
showDownPlayers .end(); ++posPlayer)
{
cout << "\n " << (*posPlayer).Ge tLastName() << "'s hand:\n\n\n";
(*posPlayer).Ge tHand().Peek();
}

Player winner = showDownPlayers .front();

for(posPlayer = showDownPlayers .begin() + 1; posPlayer !=
showDownPlayers .end(); ++posPlayer)
{
if(Evaluation:: Instance().Eval uate(ReturnComm unityCards(),
(*posPlayer).Ge tHand()) >
Evaluation::Ins tance().Evaluat e(ReturnCommuni tyCards(),
winner.GetHand( ))) winner = (*posPlayer);
else if(Evaluation:: Instance().Eval uate(ReturnComm unityCards(),
(*posPlayer).Ge tHand()) ==
Evaluation::Ins tance().Evaluat e(ReturnCommuni tyCards(),
winner.GetHand( )))
{
if((*posPlayer) .GetHand().GetT opCard().GetVal ue() >
winner.GetHand( ).GetTopCard(). GetValue())
winner = (*posPlayer);
else if((*posPlayer) .GetHand().GetT opCard().GetVal ue() ==
winner.GetHand( ).GetTopCard(). GetValue())
{
if((*posPlayer) .GetHand().GetL owPairValue() >
winner.GetHand( ).GetLowPairVal ue())
winner = (*posPlayer);
else if((*posPlayer) .GetHand().GetL owPairValue() ==
winner.GetHand( ).GetLowPairVal ue())
{
if((*posPlayer) .GetHand().GetK icker().GetValu e() >
winner.GetHand( ).GetKicker().G etValue())
winner = (*posPlayer);
}
}
}

PayWinner(winne r);
}


What is the reason to use a singleton class here? Or better, what is the
reason to use a class at all? To me it looks like you are using

Evaluation::Ins tance().Evaluat e( some_arguments )

just like a freestanding function. So why not implement it as such? If you
need to make use of preinitialized tables, a class to encapsulate static
constant data and a static evaluation function would be good enough. I do
not see a reason to actually implement a singleton pattern here and have
all those issues of lifetime management around.

So what about an implementation along those lines:

#include <vector>

// first alternative: freestanding function using static const data:
int table_lookup ( unsigned index ) {

struct my_fibb_table {

std::vector<int > data;

my_fibb_table ( unsigned length )
: data ( length )
{
if ( length > 0 ) {
data[0] = 1;
}
if ( length > 1 ) {
data[1] = 1;
}
for ( unsigned index = 2; index < length; ++index ) {
data[index] = data[index-1] + data[index-2];
}
}

int operator[] ( unsigned i ) const {
return ( data[i] );
}

};

static
my_fibb_table const table ( 20 );

return ( table[index] );

}

// second alternative: class encapsulates static const data and static
// function
class fibb {

struct my_fibb_table {

std::vector<int > data;

my_fibb_table ( unsigned length )
: data ( length )
{
if ( length > 0 ) {
data[0] = 1;
}
if ( length > 1 ) {
data[1] = 1;
}
for ( unsigned index = 2; index < length; ++index ) {
data[index] = data[index-1] + data[index-2];
}
}

int operator[] ( unsigned i ) const {
return ( data[i] );
}

};

static
my_fibb_table const table;

public:

static
int table_lookup ( unsigned index ) {
return ( table[index] );
}

};

fibb::my_fibb_t able const fibb::table ( 20 );
#include <iostream>

int main ( void ) {
std::cout << table_lookup(13 ) << '\n';
std::cout << fibb::table_loo kup(13) << '\n';
}


Best

Kai-Uwe Bux
Dec 7 '05 #2
A_*********@hot mail.com writes:
hi,

I have a singleton Evaluation class that I'm calling repeatedly in one
sequence. would someone plz have a look at the code below and tell me
if one instance of the singleton can ever "clash" with another?


If the Evaluation class is a singleton there is no other instance of it!

Impossible to say anything more without seeing the internals of Evaluation
class, but I agree with Kai-Uwe Bux about getting rid of the singleton
alltogether.

/Niklas Norrthon
Dec 7 '05 #3
Kai-Uwe Bux wrote:

What is the reason to use a singleton class here? Or better, what is the
reason to use a class at all? To me it looks like you are using

Evaluation::Ins tance().Evaluat e( some_arguments )

just like a freestanding function. So why not implement it as such? If you
need to make use of preinitialized tables, a class to encapsulate static
constant data and a static evaluation function would be good enough. I do
not see a reason to actually implement a singleton pattern here and have
all those issues of lifetime management around.


thx for your response, Kai. I am not certain I am competent enough to
follow your example however.

the Evaluate function indeed takes two arguments. first is the vector
of five Card objects returned by ReturnCommunity Cards(). second is a
reference to the Hand object returned by (*posPlayer).Ge tHand(). from
this Hand object the function extracts two more Card objects (Texas
Hold 'em "hole cards") contained therein. then these seven Cards are
examined to find the best possible hand based on their values and
suits. the function finally returns an integer indicating hand
strength.

in light of this is the singleton design justified? I want a static
class that specializes in evaluating Card objects, and I believe this
class is probably too large and cumbersome to be contained in
freestanding functions...

Dec 7 '05 #4
Niklas Norrthon wrote:
A_*********@hot mail.com writes:
hi,

I have a singleton Evaluation class that I'm calling repeatedly in one
sequence. would someone plz have a look at the code below and tell me
if one instance of the singleton can ever "clash" with another?


If the Evaluation class is a singleton there is no other instance of it!

Impossible to say anything more without seeing the internals of Evaluation
class, but I agree with Kai-Uwe Bux about getting rid of the singleton
alltogether.

/Niklas Norrthon


plz see my reply above, Niklas. the class contains more functions than
just Evaluate (which itself calls eight or so others). these include
methods of assessing "hole cards" and assigning "kickers" to hands.

Dec 7 '05 #5

A_StClai...@hot mail.com wrote:
Niklas Norrthon wrote:
A_*********@hot mail.com writes:
hi,

I have a singleton Evaluation class that I'm calling repeatedly in one
sequence. would someone plz have a look at the code below and tell me
if one instance of the singleton can ever "clash" with another?


If the Evaluation class is a singleton there is no other instance of it!

Impossible to say anything more without seeing the internals of Evaluation
class, but I agree with Kai-Uwe Bux about getting rid of the singleton
alltogether.

/Niklas Norrthon


plz see my reply above, Niklas. the class contains more functions than
just Evaluate (which itself calls eight or so others). these include
methods of assessing "hole cards" and assigning "kickers" to hands.


Well, the most important part of Niklas's reply is that there is
something wrong with your singleton if there is more than one of them.
That is what the "single" in singleton means. Either you mean
something else (perhapse factory) or your singleton is broken.

Dec 7 '05 #6
ro**********@gm ail.com wrote:

Well, the most important part of Niklas's reply is that there is
something wrong with your singleton if there is more than one of them.
That is what the "single" in singleton means. Either you mean
something else (perhapse factory) or your singleton is broken.


this is one of my first experiences with the singleton pattern so you
may be quite right about my not knowing how to use it.

I believe I have explained what my singleton Evaluation class is used
for and am open to any input regarding its appropriateness .

Dec 7 '05 #7

A_*********@hot mail.com wrote:
ro**********@gm ail.com wrote:

Well, the most important part of Niklas's reply is that there is
something wrong with your singleton if there is more than one of them.
That is what the "single" in singleton means. Either you mean
something else (perhapse factory) or your singleton is broken.
this is one of my first experiences with the singleton pattern so you
may be quite right about my not knowing how to use it.


http://en.wikipedia.org/wiki/Singleton_pattern
I believe I have explained what my singleton Evaluation class is used
for and am open to any input regarding its appropriateness .


Dec 7 '05 #8
>
Well, the most important part of Niklas's reply is that there is
something wrong with your singleton if there is more than one of them.
That is what the "single" in singleton means. Either you mean
something else (perhapse factory) or your singleton is broken.


Actually, the singleton pattern is easily broken, even by experts. One
of the 'patterns' used to implement a singleton, Double-checked
locking, turns out to not work.

http://en.wikipedia.org/wiki/Double_...ocking_pattern

(Normally wikipedia isn't the first place I'd check for info, but it
turns out to be a good reference, at least for this topic, which is
linked from the Singleton page posted in this thread)

Dec 7 '05 #9
A_*********@hot mail.com wrote:
Kai-Uwe Bux wrote:

What is the reason to use a singleton class here? Or better, what is the
reason to use a class at all? To me it looks like you are using

Evaluation::Ins tance().Evaluat e( some_arguments )

just like a freestanding function. So why not implement it as such? If
you need to make use of preinitialized tables, a class to encapsulate
static constant data and a static evaluation function would be good
enough. I do not see a reason to actually implement a singleton pattern
here and have all those issues of lifetime management around.


thx for your response, Kai. I am not certain I am competent enough to
follow your example however.

the Evaluate function indeed takes two arguments. first is the vector
of five Card objects returned by ReturnCommunity Cards(). second is a
reference to the Hand object returned by (*posPlayer).Ge tHand(). from
this Hand object the function extracts two more Card objects (Texas
Hold 'em "hole cards") contained therein. then these seven Cards are
examined to find the best possible hand based on their values and
suits. the function finally returns an integer indicating hand
strength.

in light of this is the singleton design justified? I want a static
class that specializes in evaluating Card objects, and I believe this
class is probably too large and cumbersome to be contained in
freestanding functions...


I see, the process of evaluating the strength of a hand is too complex for a
single freestanding function. So you want to take it apart into managable
pieces (that is good). Also, you want to hide those pieces from the client
code of the evaluation function as these pieces are just implementation
details (that is good, too). Hence you want them to be the private parts of
some class. So far, I am with you. However, there still is no need for a
singleton pattern. In fact, there is no need for that class to have objects
at all. Think of something like this (not run through a compiler):

// the evaluation class:
class Evaluation {

int some_helper_fun ction ( Hand const & ) {
lots of code
}

struct some_helper_str uct {

std::vector< int > some_table;

some_helper_str uct ( void ) {
initialization_ code;
}

};

static some_helper_str uct const my_table;

more_of_the_abo ve;

public:

static
int evaluate ( std::vector< Card > const &, Hand const & );

};

// initialize the static const objects of Evaluation:
Evaluation::som e_helper_struct const Evaluation::my_ table ();

int main ( void ) {

...
value = Evaluation::eva luate( card_vect, the_hand );

}

There is no need for any objects of type Evaluation, not even a single one.
Make all data of the class Evaluation static const and turn the evaluation
function into a static function of that class. No need for a singleton.

If you want to make sure that no objects of the Evaluation class are
created, make the default constructor private.
Best

Kai-Uwe Bux
Dec 7 '05 #10

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

Similar topics

2
2744
by: Rajarshi Guha | last post by:
Hi, I'm having a little problem with understanding the working of a singleton and borg class. Basically I nedd an class whose state will be shared across several modules. I found the stuff on the ASPN cookbook but it does'nt seem to be working for me. I've included some code: Borg.py: -------- class Borg: __shared_state = {} def __init__(self):
26
2502
by: Uwe Mayer | last post by:
Hi, I've been looking into ways of creating singleton objects. With Python2.3 I usually used a module-level variable and a factory function to implement singleton objects. With Python2.4 I was looking into decorators. The examples from PEP 318 http://www.python.org/peps/pep-0318.html#examples don't work - AFAIK because:
10
2659
by: E. Robert Tisdale | last post by:
Could somebody please help me with the definition of a singleton? > cat singleton.cc class { private: // representation int A; int B; public: //functions
7
2834
by: phl | last post by:
hello, My project in a web project. I choose to use singleton in one of my projects. Towards the end I realise that I seemed to have refered to the fields singleton in my other classes in my business logic a little precariously. I access my the fields in the singlton in my BLL classes directly. Is this a really bad violation of OOP rules? It's almost liek I have use the singlton as one big global variable. Is there any decent way of...
4
3056
by: Simon Hazelton | last post by:
Is it possible in VB.net to have a single or singleton instance of a class per specific database record. I'm writing an auction site and have a problem with resolving proxy bids, effectively I am creating an unlimited amount of "Auctioneers" for the site as a whole (which is definitely wrong). I could create a singleton "Auctioneer" Class for the site with a singleton but feel this would be a performance botleneck. Ideally I would...
14
3039
by: Paul Bromley | last post by:
Forgive my ignorance on this one as I am trying to use a Singleton class. I need to use this to have one instance of my Class running and I think I understand how to do this. My question however is can a singleton class have a number of paramterised constructors enabling me to pass in parameters or not? I am trying to use the following to send in a parmeter to a constructor, but getting an error with it. I have a feeling that I am not...
6
3455
by: Andre Meyer | last post by:
While looking for an elegant implementation of the singleton design pattern I came across the decorator as described in PEP318<http://www.python.org/dev/peps/pep-0318/> . Unfortunately, the following does not work, because decorators only work on functions or methods, but not on classes. def singleton(cls): instances = {} def getinstance():
3
2968
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
3
18258
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
9720
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
9599
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
10626
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...
1
10374
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
10112
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...
1
7650
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
6879
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
5546
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
4330
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.