Getting used to some new code and have a question. All over it, I am seeing the following
file1.cs :
MyClass myInstance = MyClass.Instance();
...and then in the definition of MyClass there is...
MyClass.cs :
public class MyClass {
// etc. etc.
static readonly MyClass _instance = new MyClass();
public static MyClass Instance() {
return _instance;
}
// etc. etc.
}
What's the reason for doing that as opposed to just in file1.cs :
MyClass myInstance = new MyClass();
?
Because its using single ton pattern that is the reason...
Read : Singleton - The singleton pattern is a design pattern that is used to ensure that a class can only have one concurrent instance. Whenever additional objects of a singleton class are required, the previously created, single instance is provided.
Read : Singleton with proper example
it is a "singleton pattern" you can read about it here
http://csharpindepth.com/Articles/General/Singleton.aspx
This is the singleton pattern. That's why a method is used to get the instance.
Singleton pattern is used, when we want only one instance of a class be used in our app. We don't want the consumers of our app have the right to build more than one instances.
For a detailed description of the singleton pattern, please have a look here.
This is a Singleton Pattern sometimes a new instance is not the best way to do something.
An example of this is a logger. There is no need to instantiate a logger every time one is needed hence the singleton pattern is useful.
And yet another theory about the singleton...
You use it also in situations when you would like to have a common object shared by different parts of your application. Sometimes it might be necessary that you are forced to turn a static class into a singleton so that you can use if for data binding (a static class cannot be bound).
Some typical singletons that live as long as the application lives can be settings, some kind of cache, a backgrou file uploader with file watcher etc. etc...
I would advise you to use a property instead of a function. It is cleaner, more convenient for debugging and mock testing.
Note that by using a static constructor (as you are already doing), the initialization of _instanceis thread-safe.
Note : The implementation of the other methods should not be static.
Find below the complete implementation of the singleton pattern:
public class MyClass
{
static MyClass _instance = new MyClass();
public static MyClass Instance
{
get
{
return _instance;
}
set { _instance = value; }
}
public void DoStuff()
{
//etc...
}
private MyClass()
{
}
}
And you use it in other classes this way :
MyClass.Instance.DoStuff();
Related
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()
{
}
}
I currently have a class which I instantiate when I start my program. The class itself will create a new thread and begin to search for broadcasts from routers.
I have other windows, other then MainWindow, which needs to be able to access the data stored within the instance of this class. However, I'm not sure as to how the other windows can reference this data.
Is there some other way I can store the instance of this class so that it is accessible application wide? I need it to start right when the rest of the application starts, so it seemed logical (to me) to have the class be instantiated in the first window.
namespace Lalu_WPF
{
public partial class MainWindow : Window
{
// data storage for program
public FindRouter finder = new FindRouter();
public MainWindow()
{
......
Don't make Singleton (notice the capital letter). It is error prone in multiple threads environments(muttable Singletons) and bad for testing.
What are your requirements?
Do you have to have one object in one application or one object in whole CLR?
I bet the first one.
Make an object in your App class (App.xaml.cs) and then acces it via getter
App MyApplication = ((App)Application.Current);
MyApplication.Router;
Don't use a Singleton, it makes unit testing hard and your code surprising.
Give classes which need access to an instance the instance. That means that every class which needs this single instance should accept either by a constructor argument or setter. Whoever creates the class is then in charge of supplying the dependency. This is called Dependency Injection.
You could make the class a singleton and this way you could access this same instance across the entire application. You can see an example on the msdn website here
Do you have a Program class? In the Windows Forms projects that I do, variables such as that go in Program public static readonly members or in public static properties with get only.
What you're talking about sounds like the Singleton design pattern. You could create a singleton object, a static class, or (what I like) a Monostate object (an object that encapsulates the static class or single instance) , something like this:
public class SingletonWidget
{
private static readonly Implementation SingleInstance ;
public void DoSomething( int someValue )
{
SingleInstance.DoSomething( someValue ) ;
return ;
}
public int SomeProperty
{
get
{
return SingleInstance.SomeProperty ;
}
set
{
SingleInstance.SomeProperty = value ;
}
}
static SingletonWidget()
{
SingleInstance = new Implementation() ;
return ;
}
private class Implementation
{
public void DoSomething( int someValue )
{
// ...
}
public int SomeProperty { get ; private set ; }
}
}
Usage looks like normal object instantation:
SingletonWidget foo = new SingletonWidget() ;
foo.DoSomething(3) ;
but under the covers, there's just a single instance hanging around. Changing from a static class or singleton is trivial as only the wrapper needs to change. Building stubs or mocks is pretty easy, too.
It makes it easy to
Try a DI framework or some less complex implementation of a service locator. That will allow you to provide the instance where it is needed throughout your app without hardcoding in a singleton, which is then painful to write tests around.
I know that Ninject at least provides support for single instances application-wide. I haven't used it in a WPF application but I can't see why not.
As a basic example of a service locator you could do something like the following. I've called the shared class Foo:
public interface IFoo { ... }
public class Foo { ... }
public class ServiceLocator
{
IFoo _foo = new Foo();
public IFoo GetFoo() { return _foo; }
}
public class DependsOnFoo
{
public IFoo Foo = ServiceLocator.GetFoo();
...
}
DependsOnFoo.Foo is the shared instance of Foo by default but when writing automated tests you could swap it out with a stub or mock:
var testTarget = new DependsOnFoo();
testTarget.Foo = mockFooImplementation;
// now testTarget isn't bound to the Foo implementation
As far as I understand your question is how to store a reference to your finder rather than how to create it. If this is the case I would suggest using IDictionary Application.Current.Properties property, which is nothing but a collection of application-scope properties. At startup you can create your object and store a reference to it like this:
Application.Current.Properties["finder"] = new FindRouter();
Then, in any place of your program you can access it like
FindRouter finder = (FindRouter)Application.Current.Properties["finder"];
Hope this helps.
Although a static class has only one instance and can't be instantiated, a class with a private constructor can't be instantiated (as the constructor can't be seen), so every time you call this class, this is the same one instance?
Factory classes always follow the last convention (instance class with private constructor). Why is this?
Thanks
There's nothing stopping the class with the private constructor from having a public static method which returns instances of the class:
public class NoPublicConstructor
{
private NoPublicConstructor()
{
}
public static NoPublicConstructor NewInstance()
{
return new NoPublicConstructor();
}
}
As you can see, the static method does not return the same one instance.
edit: One of the reasons factory classes do this is to be able to separate responsibility in future versions: while your code always calls the factory creation method, the author may move all the "guts" out of that class into a different one and your code won't need to know the difference. Calling that class' (public) constructor ties it to an extent to the original class implementation.
You can't* get an instance from outside the class, but you can from inside. A static method or an inner class can create and return an instance of the class with a private constructor. The static class cannot be instanced by anything.
class Foo
{
private Foo()
{
}
public class Bar
{
public Bar()
{
}
public Foo GetFoo()
{
return new Foo();
}
}
}
..
Foo.Bar fooBar = new Foo.Bar();
Foo foo = fooBar.GetFoo();
Edit: *I use the term "can't" loosely. Brian Rasmussen pointed out in the comments to the OP that another method to obtain an instance is through a call through System.Runtime.Serialization.FormatterServices, and this is external to the class itself.
Foo foo = (Foo)System.Runtime.Serialization.FormatterServices.GetSafeUninitializedObject(typeof(Foo));
Creating a class with private constructor is the common pattern for implementing a "Singleton" object.
The Singleton usually will instantiate an instance of itself, and only allow access to it through a static "Instance" property, which means there's only ever one instance of the class.
The advantage of using a Singleton over a purely static class is that you can utilize interfaces and different implementation classes within the singleton. Your "Singleton" might expose an interface for a set of methods, and you can choose which exact implementation class to instantiate under the covers. If you were using a purely static class, it would be hard to swap out a completely different implementation, without impacting other code.
The main downside of Singleton is that it's difficult to swap out the implementation class for testing, because it's controlled within the Singleton private methods, but there are ways to get around that.
public class MySingletonClass
{
public MySingletonClass()
{
_mySingletonObj = Instance();
}
public static MySingletonClass Instance()
{
if (_mySingletonObj == null)
{
lock (typeof(lockObject))
{
if (_mySingletonObj == null)
_mySingletonObj = new MySingletonClass();
}
}
return _mySingletonObj ;
}
}
MySingletonClass _myObj = new MySingletonClass();
This act as singleton with public constructors..?
Thanks
No, it's not a singleton - anyone can create multiple instances of it. (Leaving aside the stack overflow issue that's already been raised, and the fact that you're using double-checked locking unsafely.)
One of the distinguishing features of a singleton type is that it prevents more than one instance of itself from ever being constructed.
From the wikipedia Singleton Pattern article:
In software engineering, the singleton
pattern is a design pattern that is
used to restrict instantiation of a
class to one object.
From Ward Cunningham's pattern repository:
A Singleton is the combination of two
essential properties:
Ensure a class only has one instance
Provide a global point of access to it
Clearly your singleton fails to meet both these definitions.
See my singleton article for real implementations.
The code as posted does not work as a singleton, due to the public constructor, but in addition to that, there's numerous flaws and problems with the code:
Public constructor calls Instance, which calls public constructor, which calls Instance, which calls..... stack overflow imminent
Public constructor returns a new object every time it is called, you can not replace the returned result with the same object reference upon subsequent requests. In other words, public constructor on singleton breaks the pattern.
You should not leak your lock objects, which in your case you lock on the type of an object. Do not do that, instead lock on a private object.
Here's a fixed version of your code:
public class MySingletonClass
{
private readonly object _mySingletonLock = new object();
private volatile MySingletonClass _mySingletonObj;
private MySingletonClass()
{
// normal initialization, do not call Instance()
}
public static MySingletonClass Instance()
{
if (_mySingletonObj == null)
{
lock (_mySingletonLock)
{
if (_mySingletonObj == null)
_mySingletonObj = new MySingletonClass();
}
}
return _mySingletonObj;
}
}
MySingletonClass _myObj = MySingletonClass.Instance();
Check out the .NET Optimized code section at the Dofactory. This has IMO the best implementation. Also check out the site for other design pattern implementations in C#.
The constructor should be private
Instead of locking it, you could also try to create a static readonly singelton...
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
static Singleton()
{
}
private Singleton()
{
}
/// <summary>
/// The public Instance property to use
/// </summary>
public static Singleton Instance
{
get { return instance; }
}
}
The essence of Singleton is to provide :
exactly one instance of class across the system;
simple access to it.
The implementation of Singleton based on creation a class with a method(or property in .NET) that creates an instance of this class if one doesn't exists yet. The constructor of class must be private to prevent other ways of initialization. Also Singleton must be carefully used in multi-threaded applications because in one point of time, the two threads may create two different instances (which violates singleton pattern).
More details and examples you can find here.
I had another interview question. I thought this was silly, but maybe there is something I am missing. The question asked which GoF pattern this is (answer: singleton), and, if there are any problems, how I solve them.
I don't see any problems. I mentioned this is never freed and I expect that from this pattern. That is all I said. Am I missing something?
public class Class1
{
private static Class1 oInstance = null;
private Class1() { }
public static Class1 GetInstance()
{
if (oInstance == null)
{
oInstance = new Class1();
}
return oInstance ;
}
}
Thread-safety - multiple instances could be created if GetInstance() is called from competing threads.
See: An obvious singleton implementation for .NET?
There are multiple concerns you want to consider when implementing a Singleton pattern.
What happens when multiple callers request the singleton from multiple threads. It should just work.
When is the Singleton instance constructor called. You may want to defer it so it happens on the first call requesting the singleton, you may want it first instantiated at some other time.
Should people be able to inherit off your singleton class? What should the behavior be?
Should it be possible to switch your singleton instance to a different instance after the singleton has been instantiated. Answering yes to this violates the singleton pattern so in general the field holding singletons should be readonly.
API design, should you use a property or a method to return the Singleton instance.
Some people say singletons are evil. Should you even be considering it in the first place. This has been discussed quite often a good starting point is http://blogs.msdn.com/scottdensmore/archive/2004/05/25/140827.aspx
The following is a good general purpose pattern you could follow. Its thread safe, sealed, uses properties and defer instansiates the singleton.
public sealed class Singleton
{
static class SingletonCreator
{
// This may seem odd: read about this at: http://www.yoda.arachsys.com/csharp/beforefieldinit.html
static SingletonCreator() {}
internal static readonly Singleton Instance = new Singleton();
}
public static Singleton Instance
{
get { return SingletonCreator.Instance; }
}
}
Others mentioned thread safety. There's also the fact that they forgot to mark it as sealed, and so you could inherit from it and create multiple instances that way.
You have a potential race condition in multithreaded code. Two threads could each get past the null check before the constructor on the other thread is completed, so that both could end up constructing the class.
The code is not thread-safe. To make it so you need to do this:
public class Class1
{
private static Class1 oInstance = null;
private Class1() { }
public static Class1 GetInstance()
{
if (oInstance == null)
{
lock(typeof(Class1))
{
if (oInstance == null)
{
oInstance = new Class1();
}
}
}
return oInstance ;
}
}
This is the most efficient way of lazily loading the instance as it only bothers to lock (can be expensive) when it is suspected the instance won't be instantiated for the next call. Checking again once in the lock ensures it will only be instantiated once.
There is a potential issue with this if you have a multithreaded application. This can cause more than one instance to be constructed if two threads request at the same time.
I'd take a look at this page on Singletons in C#. It shows the problem in detail, as well as better options.
so is the solution the following?
public class Class1
{
private static Class1 oInstance = new Class1();
private Class1() { }
public static Class1 GetInstance()
{
return oInstance ;
}
}
Don't work at that company. The singleton pattern isn't a frequently used pattern and it's applicability in a pure OO system is questionable. Undoing a singleton pattern is a huge problem if you ever need to turn it back in to a normally constructed object.
It's missing thread-safety, this page explains it really well.