Design Patterns Simplified-part 2 (Singleton) "Brief introduction to Designing Mode-Part II (Singleton mode)"

Source: Internet
Author: User

http://www.c-sharpcorner.com/UploadFile/19b1bd/design-patterns-simplified-part-2-singleton/design Patterns Simplified-part 2 (Singleton)"Brief Introduction to Designing Mode-Part II (Singleton mode)"      

I am here to continue the explanation of Design Patterns. Today we'll explain the easiest yet an important design pattern called Singleton.

Here I continue to explain design patterns. Today I'm going to explain the simplest but most important design pattern, that is, the singleton pattern.

In case you had not had a look at our first article, go through the following link:

Assuming that you haven't read my first article, please go back and read it, here is the link:

    • Design Patterns Simplified:part 1

Before talking about it implementation let's begin with some fundamental questions as in the following.

To discuss how the singleton pattern is implemented, let's take a look at some of the underlying issues.

Use of the Singleton Pattern "Use singleton mode"

as the name suggests, the Singleton Pattern allows only one instance of a class-to is created.

Just like this name, Singleton mode allows only one instance of a class to be created.

When does we need to has only one instance of a class?

Why do we only need an instance of a class?

There is many possible requiremetns for a instance of a class but they all tend to having the one objective that we don ' t W Ant to change the state of the the object or we want to keep the class stateless.

There are many examples of possible requiremetns classes, but they all want only one object, so we can't change the state of the object or make the object's state invalid.


A Simple example could is, want to load some master data at once and let the consumers of the data make a call to The Singleton class instead of each consumer making various calls by creating a new instance.

As a simple example, you want to load the data from the main table immediately, and have a singleton class invoke the data that gets the client table, instead of creating an instance of the class for each client to invoke fetch data.

In general, in any complex enterprise application, Repository and Data Access Layer classes can be seen as a Singleton sin Ce typically we don ' t want them to maintain the state in these layers.

In general, in an enterprise application of any complex point, the classes of warehousing and data access layers can be viewed as singleton, as we do not want them to remain in these layers.

Some Other example could is cross-cutting concerns like Logging, Configuration, Caching and so forth the can also be impl Emented as a Singleton since we want a single and global point of access to these classes.
Other examples are crosscutting concerns, such as logging, system configuration, caching, and so on, which can be similarly designed as Singleton, because we want to have global, single access to these classes.


Apart from the core consideration explained above, I has seen that developers, mostly no so experienced sometimes, creat E unnecessarily instances that creates not just a overhead to memory but also impacts the overall performance of a appli cation.

In addition to the above explanation, I have seen a lot of developers, sometimes not so experienced, they create unnecessary instances, which not only increases the memory overhead, but also affects the performance of the system.

Why is not Static classes "Why not use static classes"

There can several reasons why to not use a static class however I can think of a few as follows.

As for why not use static classes, I think there are the following reasons:

    • There can cases where you want to implement interfaces (maybe to implement IOC, I'll explain IOC later) in a class th At can is done with a Singleton implementation but not in the static one.
      There may be situations where you want to implement an interface in a class "may be implementing IOC, I will descend to IOC", which can be done in a singleton, but not in a static class.
    • If required, you can use a singleton class as a method parameter whereas your cannot do and a static class.
if necessary, you can take a singleton class as a parameter to a method, but you cannot do this for static classes as well.

Special care for Singleton classes "Special to say is the Singleton class"

We need to take special care for Singleton classes. The idea of a state of a class comes with some extra care this means we need to handle synchronization issues in MULTI-THR eaded environments.

We need to specifically talk about the state of the Singleton class, the class, there are some points to note, that is, we need to handle synchronization in a multi-threaded environment.

Enough theory, now let's talk about implementation.

Well, the theory is enough, now let's talk about how to implement the singleton pattern.

Let ' s has a look at the most basic implementation.

Let's look at the most basic implementations first.

In the first example below, we had implemented a Singleton with Lazy loading since the instance would not be created until The caller calls the GetInstance method for the first time.

In the following example, I implemented a lazy-loading singleton, because this instance only creates an instance of the class when the GetInstance method is called for the first time.

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceconsoleapplication1{/// <summary>    ///Singletonclass Single-case mode learning/// </summary>    Public classSingletonclass {/// <summary>       ///Create a private, static, class-like variable/// </summary>       Private StaticSingletonclass instance =NULL; /// <summary>       ///Create a private Singletonclass parameterless constructor/// </summary>       PrivateSingletonclass () {}/// <summary>       ///Create a static property getinstance/// </summary>        Public Staticsingletonclass getinstance {Get            {               if(Instance = =NULL)               {                   //Instantiate SingletonclassInstance =NewSingletonclass (); }               returninstance; }       }    }}

Let's try to fix the sync issue, that's arise in multi-threaded environments. For this, we'll use a double-lock mechanism.

Now let's fix that, in the example above in a multithreaded environment, there may be synchronization problems. For this, I will use a double lock mechanism.

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceconsoleapplication1{/// <summary>    ///Singletonclass Single-case mode learning/// </summary>    Public classSingletonclass {/// <summary>       ///Create a private, static, class-like variable/// </summary>       Private StaticSingletonclass instance =NULL; Private Static ObjectLockme =New Object(); /// <summary>       ///Create a private Singletonclass parameterless constructor/// </summary>       PrivateSingletonclass () {}/// <summary>       ///Create a static property getinstance/// </summary>        Public Staticsingletonclass getinstance {Get            {               if(Instance = =NULL)               {                   Lock(lockme) {if(Instance = =NULL)                       {                           //Instantiate SingletonclassInstance =NewSingletonclass (); }                   }                                 }               returninstance; }       }    }}

Singleton with Static initializations. Please note that the. NET Framework guarantees thread safety for static initialization so we don ' t need extra care for SYN C Issues However we may not get the benefit of the lazy loading of objects here.

Finally, we look at the static initialization of a singleton pattern. Note that for static initialization, the. NET Framework guarantees thread safety, and we don't have to care about synchronization issues, but in this case we can't benefit from lazy loading of objects.

 Public class Singletonclass {      privatestaticnew  singletonclass ();       Private Singletonclass () {}        Public Static Singletonclass getinstance     {          get         {              return  instance;}}  }   

I hope you has liked this article. I look forward to your comments/suggestions.

I hope you like this article and look forward to your comments and suggestions.

Design Patterns Simplified-part 2 (Singleton) "Brief introduction to Designing Mode-Part II (Singleton mode)"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.