design-pattern
IT Management

Singleton Pattern – Cybarlab


The among the most basic style patterns is Singleton pattern. This pattern guarantees that a class has just one circumstances in the entire application and supplies a worldwide point of access to it.

In our application at some point we require such kind of things, which will be developed just one time in the whole application life process. That indicates, there will be just one things in the entire application and everybody will have the ability to gain access to that a person things.

We can develop this kind of class by utilizing fixed. Then we can access that class without producing brand-new circumstances.

 public class Singleton
{
personal Singleton() {}
public fixed Singleton CreateInstance().
{
return brand-new Singleton();.
}
} 

Throughout development, we require to consider about multithreaded environment. Then several resource can access that class in the very same time.

 public class Singleton.
{
personal unstable fixed Singleton uniqueInstance;.
personal fixed readonly things _ lock = brand-new things();.
personal Singleton() {}
public fixed Singleton CreateInstance().
{
if (uniqueInstance == null)// checked lock.
{
lock (_ lock).
{
if (uniqueInstance == null).
{
uniqueInstance = brand-new Singleton();.
}
}
}
return uniqueInstance;.
}
} 

Here checked lock method is utilized in order to get rid of excitedly developed circumstances issue.

Though, singleton pattern is extremely basic, however we need to utilize it extremely thoroughly. Unless it will reduce the application efficiency.


Source link