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

Singleton help please.

I am trying to set up a singleton since it seems like the best
solution to my problem.

I have a an object that I want to initialize when the program starts
then I just want to call it like a static function.... so i want to
create instances of that object. I need to send parameters to
initialize my object properly in the singleton. that is where i am
starting to have problems. I starting to wonder if this is bad style.

is this the bast way to go?

V.
Nov 16 '05 #1
9 1538
Hi,
I am trying to set up a singleton since it seems like the best
solution to my problem.

I have a an object that I want to initialize when the program starts
then I just want to call it like a static function.... so i want to
create instances of that object. I need to send parameters to
initialize my object properly in the singleton. that is where i am
starting to have problems. I starting to wonder if this is bad style.


Singleton == always the same object, always the same instance. If you want
that, use two static methods:

====================

public class SingleClass {

private SingleClass instance;

public static SingleClass InitObject( <parameters> ) {
if ( this.instance == null )
this.instance = new SingleClass( .... );

return this.instance
}

public static SingleClass GetInstance() {
if ( this.instance != null )
return this.instance;
else
return null;
}

private SingleClass( ... ) {

// Init
}
}

======================

Regards,

Frank Eller
www.frankeller.de
Nov 16 '05 #2
VidalSasoon <vi*********@bootbox.net> wrote:
I am trying to set up a singleton since it seems like the best
solution to my problem.

I have a an object that I want to initialize when the program starts
then I just want to call it like a static function.... so i want to
create instances of that object. I need to send parameters to
initialize my object properly in the singleton. that is where i am
starting to have problems. I starting to wonder if this is bad style.

is this the bast way to go?


Well, you could adapt the normal singleton pattern by having a method
to set the instance (with parameters), and a property which returns the
instance if it's been set up and throws an exception otherwise.

(The set method would throw an exception if called twice.)

For true thread-safety, you should make sure there's a memory barrier
between the set and every get, but chances are you'll be fine without
it. If you want it though, just using a simple lock for both the set
and the get would do the trick nicely, and won't cost too much unless
you're fetching the instance *loads* of times.

Another alternative is to use the normal singleton pattern (see
http://www.pobox.com/~skeet/csharp/singleton.html) but make the
initializer fetch the parameters from wherever it needs to.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #3
Frank Eller [MVP] <fe******@frankeller.de> wrote:
I have a an object that I want to initialize when the program starts
then I just want to call it like a static function.... so i want to
create instances of that object. I need to send parameters to
initialize my object properly in the singleton. that is where i am
starting to have problems. I starting to wonder if this is bad style.
Singleton == always the same object, always the same instance. If you want
that, use two static methods:


<snip>
public static SingleClass GetInstance() {
if ( this.instance != null )
return this.instance;
else
return null;
}


This won't compile, as "this" doesn't exist in a static method. Even if
it did, the if clause is somewhat redundant, is it not? The above is
exactly equivalent to

public static SingleClass GetInstance()
{
return this.instance;
}

(which still doesn't compile, of course).

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #4
"VidalSasoon" wrote:
[...]
I have a an object that I want to initialize when the program starts
then I just want to call it like a static function.... so i want to
create instances of that object. I need to send parameters to
initialize my object properly in the singleton. that is where i am
starting to have problems. I starting to wonder if this is bad style.
[...]


Hi,

take a look at this singleton implementation:

public sealed class Singleton

{

private static readonly Singleton m_Instance = new Singleton( );

private Singleton( ) { }

static Singleton( ) { }

public static Singleton Instance

{

get { return m_Instance; }

}

}

thread-safe and good performance.

<http://weblogs.netug.de/hgzigann/articles/329.aspx>

--
Hans-Gerd Zigann - <hg******@web.de>
..NET Blog @ http://weblogs.netug.de/hgzigann
Nov 16 '05 #5
Heck, you're right. I shouldn't write down stuff right from my mind ...
*Sigh* ...

Regards,

Frank

Jon Skeet [C# MVP] wrote:
Frank Eller [MVP] <fe******@frankeller.de> wrote:
I have a an object that I want to initialize when the program starts
then I just want to call it like a static function.... so i want to
create instances of that object. I need to send parameters to
initialize my object properly in the singleton. that is where i am
starting to have problems. I starting to wonder if this is bad
style.


Singleton == always the same object, always the same instance. If
you want that, use two static methods:


<snip>
public static SingleClass GetInstance() {
if ( this.instance != null )
return this.instance;
else
return null;
}


This won't compile, as "this" doesn't exist in a static method. Even
if it did, the if clause is somewhat redundant, is it not? The above
is exactly equivalent to

public static SingleClass GetInstance()
{
return this.instance;
}

(which still doesn't compile, of course).

Nov 16 '05 #6
Alternatively...

using System;

namespace TestStatic1
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
///

static private int classID= 0;
static private bool isInit= false;
static public bool InitClassID(int i)
{
lock(typeof(Class1))
{
if (isInit || i<0) {return false;}
else
{
isInit= true;
classID= i;
return true;
}
}
}
static private int GetClassID()
{
lock(typeof(Class1))
{
return classID++;
}
}

private int id;
public Class1()
{
if (!Class1.isInit)
{
throw new IndexOutOfRangeException("Class Not Init.");
}
else
{
this.id= GetClassID();
}
}
public int ID
{
get{return id;}
}
[STAThread]
static void Main(string[] args)
{
//
// TODO: Add code to start application here
//
try
{
Class1 c1= new Class1();
System.Console.WriteLine(c1.ID); // 1
}
catch (Exception e)
{
System.Console.WriteLine(e);
}
Class1.InitClassID(100);
Class1 c2= new Class1();
System.Console.WriteLine(c2.ID); // 100
Class1.InitClassID(100);
Class1 c3= new Class1();
System.Console.WriteLine(c3.ID); // 101
System.Console.ReadLine();

}
}
}
Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #7
Hans-Gerd Zigann <hg******@web.de> wrote:
"VidalSasoon" wrote:
[...]
I have a an object that I want to initialize when the program starts
then I just want to call it like a static function.... so i want to
create instances of that object. I need to send parameters to
initialize my object properly in the singleton. that is where i am
starting to have problems. I starting to wonder if this is bad style.
[...]


take a look at this singleton implementation:

public sealed class Singleton
{
private static readonly Singleton m_Instance = new Singleton( );


Yes, that's a fine Singleton implementation (although it sacrifices
some performance in order to get true laziness). However, it doesn't
address the OP's issue of initializing the singleton with parameters.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #8
Jon Skeet [C# MVP] <sk***@pobox.com> wrote in message news:<MP************************@msnews.microsoft. com>...
VidalSasoon <vi*********@bootbox.net> wrote:
I am trying to set up a singleton since it seems like the best
solution to my problem.

I have a an object that I want to initialize when the program starts
then I just want to call it like a static function.... so i want to
create instances of that object. I need to send parameters to
initialize my object properly in the singleton. that is where i am
starting to have problems. I starting to wonder if this is bad style.

is this the bast way to go?


Well, you could adapt the normal singleton pattern by having a method
to set the instance (with parameters), and a property which returns the
instance if it's been set up and throws an exception otherwise.

(The set method would throw an exception if called twice.)

For true thread-safety, you should make sure there's a memory barrier
between the set and every get, but chances are you'll be fine without
it. If you want it though, just using a simple lock for both the set
and the get would do the trick nicely, and won't cost too much unless
you're fetching the instance *loads* of times.

Another alternative is to use the normal singleton pattern (see
http://www.pobox.com/~skeet/csharp/singleton.html) but make the
initializer fetch the parameters from wherever it needs to.


I'm making a 3d app so I call this singleton about 100 times a second.
I tried it without locks and it seems it would sometimes get a
NullReferenceException. I think I know what I did wrong though. It's
gonna work.

thanks for all the info :)
V.
Nov 16 '05 #9
VidalSasoon <vi*********@bootbox.net> wrote:
Another alternative is to use the normal singleton pattern (see
http://www.pobox.com/~skeet/csharp/singleton.html) but make the
initializer fetch the parameters from wherever it needs to.


I'm making a 3d app so I call this singleton about 100 times a second.
I tried it without locks and it seems it would sometimes get a
NullReferenceException. I think I know what I did wrong though. It's
gonna work.


100 times a second is no problem at all if you need to go with a
solution which uses locks. If you were going to use the property
hundreds of *thousands* of times a second, that might be different.
Don't forget that you can always call the property once and use the
same reference several times.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #10

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

Similar topics

10
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
3
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...
5
by: Pelle Beckman | last post by:
Hi, I've done some progress in writing a rather simple singleton template. However, I need a smart way to pass constructor arguments via the template. I've been suggested reading "Modern C++...
7
by: Marc Pelletier | last post by:
Hello, I am still fairly new to CSharp and am trying to implement a singleton pattern. I found Jon Skeet's excellent page (http://www.yoda.arachsys.com/csharp/singleton.html), but am struggling...
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...
2
by: Michel van den Berg | last post by:
Hello, I tried to implement the GoF Singleton Pattern. What do you think? Public MustInherit Class Singleton(Of T As New) Public Sub New() If SingletonCreator.Creating = False Then Throw...
9
by: Marcel Hug | last post by:
Hallo NG ! I Have a little question about inheritance of a singleton class. In my application i have a Database-Connection Lib, in which I would šlike to connect different databases of the same...
5
by: Rich | last post by:
The following code produced a singleton object with application scope when it should have had page scope: public class Singleton { private static Singleton uniqueInstance = null; private...
3
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...
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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...
0
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...
0
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,...
0
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...

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.