What is the design pattern?


The design patterns are the recurring solution to recurring problem in Software architecture.
OR
Design pattern are the time tested practices for OOP problem. It is the process of solving object oriented programming language in much better ways.

There are 3 basic classification o design pattern

1. Creational patterns
2. Structural Patterns
3. Behavioral Pattern

Now let see some example of Creational Patterns example

1. Singleton Pattern
2. Abstract Factory Pattern
3. Factory Method pattern
4. Prototype Pattern
5. Builder Pattern

Singleton Pattern:

In this design pattern, we can create only one instance of Class. That instance needs to be accessible in different part of application. It can be use as global.
For example, we can use this pattern in so many scenarios like logging, Database access, and Holding Database Connection instance etc.

This pattern can be achieved by

1. Creating private construct of class.
2. Creating Instances and Method as static.

Now create the class like given below

namespace WebApplication2
{
    public class SingleTonTest
    {
        public static int intCounter;
 
        private SingleTonTest()
        {
        }
 
        public static void Hit()
        {
            intCounter++;
        }
 
        public static int getTotalHits()
        {
            return intCounter;
        }
    }
}

Step 2 Write the code in UI Layer like this

using System;
 
namespace WebApplication2
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
 
        protected void Button1_Click(object sender, EventArgs e)
        {
            HiCounter();
        }
 
        private void HiCounter()
        {
            SingleTonTest.Hit();
            Label1.Text = SingleTonTest.getTotalHits().ToString();
        }
 
        protected void Button2_Click(object sender, EventArgs e)
        {
            HiCounter();
        }
    }
}

Summary:

Here we learnt that how to use singleton design pattern in C#.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.