Using singleton instead of a global static instance

Posted by Farstucker on Stack Overflow See other posts from Stack Overflow or by Farstucker
Published on 2010-04-06T22:56:27Z Indexed on 2010/04/07 4:13 UTC
Read the original article Hit count: 396

Filed under:
|
|

I ran into a problem today and a friend recommended I use a global static instance or more elegantly a singleton pattern. I spent a few hours reading about singletons but a few things still escape me.

Background: What Im trying to accomplish is creating an instance of an API and use this one instance in all my classes (as opposed to making a new connection, etc).

There seems to be about 100 ways of creating a singleton but with some help from yoda I found some thread safe examples. ..so given the following code:

public sealed class Singleton
{
     public static Singleton Instance { get; private set; }

     private Singleton()
     {
        APIClass api = new APIClass();  //Can this be done?
     }

     static Singleton() { Instance = new Singleton(); }
}

How/Where would you instantiate the this new class and how should it be called from a separate class?

EDIT: I realize the Singleton class can be called with something like

Singleton obj1 = Singleton.Instance();

but would I be able to access the methods within the APIs Class (ie. obj1.Start)? (not that I need to, just asking)

EDIT #2: I might have been a bit premature in checking the answer but I do have one small thing that is still causing me problems. The API is launching just fine, unfortunately Im able to launch two instances?

New Code

public sealed class SingletonAPI
{
 public static SingletonAPI Instance { get; private set; }

 private SingletonAPI() {}

 static SingletonAPI() { Instance = new SingletonAPI(); }     

 // API method:
 public void Start() { API myAPI = new API();}
 }

but if I try to do something like this...

SingletonAPI api = SingletonAPI.Instance;
api.Start();
SingletonAPI api2 = SingletonAPI.Instance;  // This was just for testing.
api2.Start();

I get an error saying that I cannot start more than one instance.

© Stack Overflow or respective owner

Related posts about c#

Related posts about singleton