Static constructor - Singleton Design pattern in c# - c#

What if, I replaced private constructor with a static constructor in singleton Design pattern?
public sealed class Singleton
{
private static Singleton instance=null;
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
Static constructor will be called only once and I couldn't find any difference in the implementation. Can we replace private with static constructor?

All that the private constructor is really doing in this case is preventing anything outside of the class from instantiating an instance of class Singleton, which is almost certainly intentional as a singleton should only have a single instance.
Static class constructors are run once for a type, at an unknown time, before the type, or any of it's static members, is to be utilized. Static fields are initialized before the static constructor would be run.
So, I suppose you could replace the constructor with a static one, but that would then give you the implicit parameter-less constructor on the Singleton Type, which would allow anyone to instantiate an instance, which is likely at odds with why you are using the singleton pattern in the first place. It also wouldn't change anything about how your class was being constructed, really, so why do it?
Take the following class as an example:
public class Test { }
Under the covers, because there is no declared constructor, the C# compiler implicitly adds a parameterless, public constructor to the class, allowing consumers to create an instance.
public class Program {
public static void Main() {
var test = new Test();
}
}
This is all fine and good if you want to be able to make instances of your class. The singleton pattern intends to only provide a single instance of a type to the consumers. We could add this static instance to our test type like so:
public class Test { public static Test Instance {get;} = new Test(); }
and we would be able to get this static instance like so:
public class Program {
public static void Main() {
var test = Test.Instance; // good
var other = new Test(); // less than ideal
}
}
So we are providing access to our singleton object through it's instance field, as expected, but we can still create instances of the singleton type, which is less good, as it goes against the purpose of a singleton (namely, having only a single shared instance.)
So we add a private, parameterless constructor to the type.
public class Test {
private Test() {}
public static Test Instance {get;} = new Test();
}
Adding a constructor to a type will cause the C# compiler not to add an implicit public parameter-less constructor. Making it private allows it to be accessed within the class scope, which is used for instantiating our instance property, and prevents anything else from instantiating the object. The end result being:
public class Program {
public static void Main() {
var test = Test.Instance; // good
var other = new Test(); // Compile time error
}
}
Your singleton object now prevents other instances of the class from being instantiated, and the only way to use it is through the instance property as intended.

In simple terms, if you remove the private constructor, then anyone will be able to create a new instance of Singleton:
// With the private constructor, the compiler will prevent this code from working.
// Without it, the code becomes legal.
var newInstance = new Singleton();
And if anyone can instantiate Singleton as above, then you no longer have a singleton.

Another cleaner way to do it is to use readonly on you private instance.
This is less code and also thread safe. The CLR takes care of everything for you, no need for lock , check for null and stuff.
public sealed class Singleton
{
private static readonly Singleton _instance = new Singleton();
public static Singleton Instance {
get {
return _instance;
}
}
private Singleton()
{
}
}
Then simply test:
[TestMethod]
public void IsSingleton()
{
Assert.AreSame(Singleton.Instance, Singleton.Instance);
}
EDIT:
example using lock
public sealed class Singleton
{
private static readonly object _lock = new object();
private static Singleton instance = new Singleton();
public static Singleton Instance
{
get
{
lock(_lock)
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
private Singleton()
{
}
}

In simplest terms, if you remove private, the default public constructor will get exposed. Then outsiders will be allowed to use new Singleton(); and make number of instances of Singleton class. So no Singleton Pattern will be there.
Additionally this classic implementation of Singleton pattern (private constructor + static getInstance() with either lazy-loading or eager loading) is so evil. In modern day you must switch to a Dependency-Injection framework instead.

This should work just fine. You could also make the class static and generic so you can store whatever kind of value in instance you want it to hold. This would facilitate the separation of concerns, keeping the singleton pattern and the class that it will contain separate.

Related

Make a 'new' object/class global in C# [duplicate]

What is a Singleton and when should I use it?
A singleton is a class which only allows one instance of itself to be created - and gives simple, easy access to said instance. The singleton premise is a pattern across software development.
There is a C# implementation "Implementing the Singleton Pattern in C#" covering most of what you need to know - including some good advice regarding thread safety.
To be honest, It's very rare that you need to implement a singleton - in my opinion it should be one of those things you should be aware of, even if it's not used too often.
You asked for C#. Trivial example:
public class Singleton
{
private Singleton()
{
// Prevent outside instantiation
}
private static readonly Singleton _singleton = new Singleton();
public static Singleton GetSingleton()
{
return _singleton;
}
}
What it is: A class for which there is just one, persistent instance across the lifetime of an application. See Singleton Pattern.
When you should use it: As little as possible. Only when you are absolutely certain that you need it. I'm reluctant to say "never", but there is usually a better alternative, such as Dependency Injection or simply a static class.
another way to implement singleton in c#, i personally prefer this way because you can access the instance of the singeton class as a property instead of a method.
public class Singleton
{
private static Singleton instance;
private Singleton() { }
public static Singleton Instance
{
get
{
if (instance == null)
instance = new Singleton();
return instance;
}
}
//instance methods
}
but well, as far as i know both ways are considered 'right' so it's just a thing of personal flavor.
using System;
using System.Collections.Generic;
class MainApp
{
static void Main()
{
LoadBalancer oldbalancer = null;
for (int i = 0; i < 15; i++)
{
LoadBalancer balancerNew = LoadBalancer.GetLoadBalancer();
if (oldbalancer == balancerNew && oldbalancer != null)
{
Console.WriteLine("{0} SameInstance {1}", oldbalancer.Server, balancerNew.Server);
}
oldbalancer = balancerNew;
}
Console.ReadKey();
}
}
class LoadBalancer
{
private static LoadBalancer _instance;
private List<string> _servers = new List<string>();
private Random _random = new Random();
private static object syncLock = new object();
private LoadBalancer()
{
_servers.Add("ServerI");
_servers.Add("ServerII");
_servers.Add("ServerIII");
_servers.Add("ServerIV");
_servers.Add("ServerV");
}
public static LoadBalancer GetLoadBalancer()
{
if (_instance == null)
{
lock (syncLock)
{
if (_instance == null)
{
_instance = new LoadBalancer();
}
}
}
return _instance;
}
public string Server
{
get
{
int r = _random.Next(_servers.Count);
return _servers[r].ToString();
}
}
}
I took code from dofactory.com, nothing so fancy but I find this far good than examples with Foo and Bar additionally book from Judith Bishop on C# 3.0 Design Patterns has example about active application in mac dock.
If you look at code we are actually building new objects on for loop, so that creates new object but reuses instance as a result of which the oldbalancer and newbalancer has same instance, How? its due to static keyword used on function GetLoadBalancer(), despite of having different server value which is random list, static on GetLoadBalancer() belongs to the type itself rather than to a specific object.
Additionally there is double check locking here
if (_instance == null)
{
lock (syncLock)
{
if (_instance == null)
since from MSDN
The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released.
so every-time mutual-exclusion lock is issued, even if it don't need to which is unnecessary so we have null check.
Hopefully it helps in clearing more.
And please comment if I my understanding is directing wrong ways.
A Singleton (and this isn't tied to C#, it's an OO design pattern) is when you want to allow only ONE instance of a class to be created throughout your application. Useages would typically include global resources, although I will say from personal experience, they're very often the source of great pain.
Whilst the there can only ever be one instance of a singleton, it is not the same as a static class. A static class can only contain static methods and can never be instantiated, whereas the instance of a singleton may be used in the same way as any other object.
It's a design pattern and it's not specific to c#. More about it all over the internet and SO, like on this wikipedia article.
In software engineering, the singleton
pattern is a design pattern that is
used to restrict instantiation of a
class to one object. This is useful
when exactly one object is needed to
coordinate actions across the system.
The concept is sometimes generalized
to systems that operate more
efficiently when only one object
exists, or that restrict the
instantiation to a certain number of
objects (say, five). Some consider it
an anti-pattern, judging that it is
overused, introduces unnecessary
limitations in situations where a sole
instance of a class is not actually
required, and introduces global state
into an application.
You should use it if you want a class that can only be instanciated once.
I use it for lookup data. Load once from DB.
public sealed class APILookup
{
private static readonly APILookup _instance = new APILookup();
private Dictionary<string, int> _lookup;
private APILookup()
{
try
{
_lookup = Utility.GetLookup();
}
catch { }
}
static APILookup()
{
}
public static APILookup Instance
{
get
{
return _instance;
}
}
public Dictionary<string, int> GetLookup()
{
return _lookup;
}
}
What is a singleton :
It is a class which only allows one instance of itself to be created, and usually gives simple access to that instance.
When should you use :
It depends on the situation.
Note : please do not use on db connection, for a detailed answer please refer to the answer of #Chad Grant
Here is a simple example of a Singleton:
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
private Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
You can also use Lazy<T> to create your Singleton.
See here for a more detailed example using Lazy<T>
Here's what singleton is: http://en.wikipedia.org/wiki/Singleton_pattern
I don't know C#, but it's actually the same thing in all languages, only implementation differs.
You should generally avoid singleton when it's possible, but in some situations it's very convenient.
Sorry for my English ;)
I know it's very late to answer the question but with Auto-Property you can do something like that:
public static Singleton Instance { get; } = new Singleton();
Where Singleton is you class and can be via, in this case the readonly property Instance.
Thread Safe Singleton without using locks and no lazy instantiation.
This implementation has a static constructor, so it executes only once per Application Domain.
public sealed class Singleton
{
static Singleton(){}
private Singleton(){}
public static Singleton Instance { get; } = new Singleton();
}
E.X You can use Singleton for global information that needs to be injected.
In my case, I was keeping the Logged user detail(username, permissions etc.) in Global Static Class. And when I tried to implement the Unit Test, there was no way I could inject dependency into Controller classes. Thus I have changed my Static Class to Singleton pattern.
public class SysManager
{
private static readonly SysManager_instance = new SysManager();
static SysManager() {}
private SysManager(){}
public static SysManager Instance
{
get {return _instance;}
}
}
http://csharpindepth.com/Articles/General/Singleton.aspx#cctor
Fourth version from Implementing the Singleton Pattern in C#
One shortcut you can take with this implementation (and only this one) is to just make instance a public static readonly variable, and get rid of the property entirely. This makes the basic skeleton code absolutely tiny!
public sealed class Singleton
{
public static readonly Singleton Instance = new Singleton();
static Singleton()
{
}
private Singleton()
{
}
}

How are static constructors and private constructors different?

How are static constructors and private constructors different?
public class WorkstationDevicePresenter
{
private WorkstationDevicePresenter()
{}
}
What's the point in leaving them blank?
Whats the point in leaving them blank?
There are a number of reasons to make "blank" constructors.
You might make a blank constructor because you want a place to set a breakpoint during debugging.
You might make a blank static constructor because doing so changes the semantics of static field initializers. Read Jon's article on the subject for details.
Let's leave static constructors and consider blank instance constructors.
The key rule that motivates blank constructors is: By default if there are no constructors in a type then you get a "blank" parameterless public constructor for free. If there are any constructors in a type then you do not get a blank parameterless public constructor for free.
So the first obvious reason why you'd want a blank constructor is: I want a blank parameterless constructor, but I've already made another ctor, so I no longer get one for free.
The second reason is that you don't have any ctors and you do not want a blank parameterless public constructor. You might want a blank parameterless private, internal or protected constructor. If that's what you want then you'll have to make one yourself.
In particular, making an empty private ctor as the only ctor means that the class cannot be instantiated via a constructor from outside the class. This is very useful if you want to use the factory pattern. It also prevents code outside the class from making derived classes, because derived classes must be able to call a constructor. If all the constructors are private then they can't derive.
I frequently use this variation on the factory pattern:
public abstract class Thing
{
private Thing() {}
private class RedThing : Thing { ... }
public static Thing GetRedThing() { return new RedThing(); }
}
See, by making a private constructor I can make a public abstract class that can only be instantiated by my code and only extended by my code, and therefore I have a nice invariant: every time I see an object of type Thing, I know where it came from.
Static constructors happen once when the class is loaded, private constructors happen when they are called by some public static method typically used to create singletons, or with the Builder pattern. There is no reason to have a blank private constructor (that I know of).
Static constructors initialize the static parts of a class and private constructors can only be used by the class itself, like for creating a singleton-object of the class.
public class MyClass {
private static int staticitem;
private int instanceitem;
static MyClass(){
staticitem = 0; //define value for staticitem
}
private MyClass() { //can only be called from within the class
instanceitem = 0; //define value for instanceitem
}
public static MyClass GetMyClass() {
MyClass m = new MyClass();
return m;
}
}
Blank private constructor will make the class uninstantiable by anything other than itself. If you don't have this piece of code, by default the compiler creates a blank public parameterless contstructor.
Static constructor is called when creating the static instance.
You can use both to create a Singleton pattern, for instance.
Check the following code:
public class Singleton
{
public static Singleton Instance;
static Singleton
{
Instance = new Singleton();
}
private Singleton()
{
}
}
public class SomeOtherClass
{
public static Singleton CompileError = new Singleton();
public static Singleton CompileOK = Singleton.Instance;
}

C# singleton definition

I saw implementation like that:
class MyClass
{
private static readonly MyClass _instance = new MyClass();
public static MyClass Instance{
get{ return _instance; }
}
}
Why not make it simple?
class MyClass
{
public static readonly MyClass Instance = new MyClass();
}
You can expose public fields like this - but I prefer not to. If you leave it as a property, you can change the implementation later. For example, suppose you later add a static method which you want to be able to call without initializing the singleton - with the property version, you could change the code to:
public sealed class MyClass
{
public static MyClass Instance { get { return InstanceHolder.instance; } }
private MyClass() {}
private static class InstanceHolder
{
internal static readonly MyClass instance = new MyClass();
}
public static void Foo()
{
// Calling this won't initialize the singleton
}
}
(With the original version, the singleton might be initialized, or it might not be - it's up to the CLR.)
That's just one example of why you might want to change the implementation later. With a property, you can do that - with a field, you can't.
What you've got there would work fine, but public fields are usually frowned upon in favour of Properties. You can change the implementation of the get { ... } without needing to change calling code. This would enable you to (for example) switch to lazy initialisation where the Instance is only created the first time it is used.
Note that although the calling code wouldn't need to change, it would change the signature of your class since a readonly property is different to a readonly field.

Possible to use a singleton with a non-default constructor in C#?

This is a slight variance of this question: Possible to use a singleton with a non-default constructor in C#?
I have a class that takes parameters for it's constructor. I would like to make this singleton such that the parameters are taken upon initialising the singleton and thus would not need to be passed in each time the instance is retrieved.
My solution (which is not elegant) for this is to have a CreateInstance() static method that takes the parameters and constructs the singleton instance. I would then have another static method GetInstance() which would be parameterless to obtain the singleton instance. In code, I would then need to ensure the logic calls CreateInstance before any calls to GetInstance. However, I cannot enforce this at compile time. I can, however, check at runtime by throwing an exception in GetInstance if it is called before CreateInstance.
Is there anyway I can achieve this behaviour with compile time enforcement? Or at the very least, is there a better way of doing the same thing?
There is no way to do it at compile time, because that would be like asking the compiler "can you prove that code X is never executed before code Y is executed, in the presence of multiple threads?". It cannot be done.
As for the runtime behavior of your design, I think this is as good as it can ever be.
You can make it slightly better by exposing a Func<SingletonType> property in your singleton class. When someone asks for the singleton instance and the instance has not already been created, your class would call this "factory method" to construct the singleton. If the factory method is null, then you either throw an exception or (if applicable) construct using some default parameters.
What this does is essentially defer the construction of the singleton until it's actually needed for the first time, so it's some improvement. But the underlying principle is the same.
Update:
As LukeH points out, this is pretty much what Lazy<T> does (.NET 4 only). If possible, use that one instead of writing your own.
In a classic singleton, the real magic happens in static readonly which creates the instance as soon as it is used:
public class MySingleton
{
private static readonly _instance = new MySingleton();
private MySingleton() {}
public static MySingleton Instance
{
get
{
return _instance;
}
}
}
If you have parameters to pass to constructor, you have to implement locking yourself (note the double if sandwitching the lock):
public class MySingletonWithConstructor
{
private static _instance;
private static object _lock = new Object();
private MySingletonWithConstructor(string myArg)
{
// ... do whatever necessary
}
public static MySingletonWithConstructor Instance
{
get
{
if(_instance==null)
{
lock(_lock)
{
if(_instance==null) // double if to prevent race condition
{
_instance = new MySingletonWithConstructor("Something");
}
}
}
return _instance;
}
}
}
You could just have GetInstance() call the CreateInstance() method if the singleton object doesn't exist already.
I would do it similar to this. You may have to add locks or other things to ensure:
public class ClassA {
private static ClassA instance;
private int param;
private ClassA(int param) {
this.param = param;
}
public static ClassA getInstance() {
if (instance == null) {
throw new CustomException("Not yet initialised");
} else {
return instance;
}
}
public static void createInstance(int param) {
if (instance == null) {
instance = new ClassA(param);
}
}
}
In your GetInstance() method, why dont you just call CreateInstance if your value is null, then you have lazy initialisation..
Use CreateInstance() to be the loader of a Lazy<T> and have GetInstance return the Lazy.Value (you might want to create a static readonly field that is set to = thelazy.Value to ensure a single entry into CreateInstance())

Using singleton instead of a global static instance

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.
Why not just add a public APIClass property to your singleton?
public sealed class Singleton
{
public static Singleton Instance { get; private set; }
private APIClass _APIClass;
private Singleton()
{
_APIClass = new APIClass();
}
public APIClass API { get { return _APIClass; } }
static Singleton() { Instance = new Singleton(); }
}
Then your calling site looks like:
Singleton.Instance.API.DoSomething();
Or if you are the author of the API class, you could make it a singleton itself, instead of wrapping it in a singleton:
public sealed class SingletonAPI
{
public static SingletonAPI Instance { get; private set; }
private SingletonAPI() {}
static SingletonAPI() { Instance = new SingletonAPI(); }
// API method:
public void DoSomething() { Console.WriteLine("hi"); }
}
API call:
SingletonAPI.Instance.DoSomething();
Here is the official Microsoft approach.
The beauty of the singleton is that you can use and access it anywhere in your code without having to create an instance of the class. In fact that is it's raison d'etre, a single instance of a class eg
Singleton.Instance.MyValue and Singleton.Instance.DoSomething();
You wouldn't instantiate the class - the pattern you're using basically instantiates itself the first time it's used. The advantage to the method you're using is that it's thread safe (will only instantiate once, no matter how many threads try to access it), lazy (it won't instantiate until you try to access the Singleton class), and simple in implementation.
All you need to do to use this is to do:
Singleton.Instance.MyMethodOnSingleton();
Or, alternatively:
Singleton myInstance = Singleton.Instance; // Will always be the same instance...
myInstance.DoSomething();

Categories

Resources