Close Menu
SalesforceCodex
    Facebook X (Twitter) Instagram
    Trending
    • How to Build a Generic Modal Window in Lightning Web Component
    • Top 10 Salesforce Flow Features of Salesforce Summer ’25
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    • How to Suppress PMD Warnings in Salesforce Apex
    • Top 10 PMD Issues Salesforce Developers Should Focus on in Apex
    • How to Use Graph API for Outlook-Salesforce Connection
    Facebook X (Twitter) Instagram
    SalesforceCodex
    Subscribe
    Thursday, May 29
    • Home
    • Architecture
    • Salesforce
      • News
      • Apex
      • Integration
      • Books Testimonial
    • Questions
    • Certification
      • How to Prepare for Salesforce Integration Architect Exam
      • Certification Coupons
    • Integration Posts
    • Downloads
    • About Us
      • Privacy Policy
    SalesforceCodex
    Home»Architecture»Practical Approach to Singleton Design Pattern

    Practical Approach to Singleton Design Pattern

    Dhanik Lal SahniBy Dhanik Lal SahniMay 2, 2018Updated:March 19, 2023No Comments5 Mins Read
    Facebook Twitter Pinterest LinkedIn Tumblr Email
    Practical Approach to Singleton Design Pattern
    Share
    Facebook Twitter LinkedIn Pinterest Email

    Singleton Design Pattern is used when we want to ensure that only one object of a particular class need to be created. All other objects will refer that object to get values. This pattern create object so it falls under Creation Pattern of Gang Of Four design patterns.

    Condition for Singleton Design Pattern:

    Singleton Design Pattern need to be implemented where below three requirements are satisfied

    1. Controls concurrent access to a shared resource
    2. Access to the shared resource will be requested from multiple, disparate parts of the system
    3. There can only be one object of class

    Some Example where we can use Singleton Design Pattern:

    There are many scenerio where we can use Single Design Pattern. Belwo are some real time tasks where we should use Singleton Pattern.

    • File Logging Framework
    • Application Configuration Reader
    • Connection Pool Creation
    • Print Pooler
    • Utility class like Math

    Step By Step Creation of Singleton Object

    Requirement:

    We need to create File Logging Framework for our application. That should be shared by complete application but we don’t want object more than one.

    Step 1. First step will be to create a class which wrire log in a file which is saved in application directory.

        public class LogWriter
        {
            private string m_exePath = string.Empty;
            public void LogWrite(string logMessage)
            {
                m_exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                try
                {
                    using (StreamWriter w = File.AppendText(m_exePath + "\\" + "log.txt"))
                    {
                        Log(logMessage, w);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            private void Log(string logMessage, TextWriter txtWriter)
            {
                try
                {
                    txtWriter.Write("\r\nLog Entry : ");
                    txtWriter.WriteLine("{0} {1} : {2}", DateTime.Now.ToShortDateString(),
                        DateTime.Now.ToShortTimeString(), logMessage);
                    txtWriter.WriteLine("-------------------------------");
                }
                catch (Exception ex)
                {
                    throw ex; 
                }
            }
        }
    

    This code will work fine and it will write logs. There are two problem here, we can create multiple objects and we can inherit this in another class.

        LogWriter log1 = new LogWriter();
        log1.LogWrite("Hello1");
                
        LogWriter log2 = new LogWriter();
        log2.LogWrite("Hello2");
    
        Log Entry : 9/5/2017 2:15 AM : Hello1
        -------------------------------
        Log Entry : 9/5/2017 2:15 AM : Hello2
        -------------------------------
    

    Let us resolve both issues one by one.
    Step 2. Stop creation of multiple objects.

    We can stop creation of object using private constructor. Now as user can not create object, we have to give object using another way. Let us give object using property Logger.

        public static LogWriter _Logger;
        private LogWriter()
        {
        }
        public static LogWriter Logger
        {
            get
            {
                if (_Logger==null)
                    _Logger = new LogWriter();
                return _Logger;
            }
        }
    

    Now we can not use LogWriter class using above object creation. We have to use this like below.

        LogWriter log1 = LogWriter.Logger; // No Need to create object. This will return Logger Object.
        log1.LogWrite("Hello1");
                
        LogWriter log2 = LogWriter.Logger;
        log2.LogWrite("Hello2");
    

    Step 3. Stop inheriting

    We can stop inheritance using sealed keyword. so class will be created like below.

        public sealed class LogWriter
    

    Now singleton class is almost ready. We may face issue only when multiple thread of application are executed. All thread will try to access LogWriter class. It may situation that threads executing property Logger. So there is chance that two object will be created. So let us make Logger property thread safe.

        private static readonly object obj = new object();
        public static LogWriter Logger
        {
            get
            {
                if (_Logger == null)  //double lock pattern
                {
                    lock (obj)
                    {
                        if (_Logger == null)
                            _Logger = new LogWriter();
                    }
                }
                return _Logger;
            }
        }
    

    We have implemented double lock pattern , in case one thread is try to lock the object and other thread at same time try to create object. This pattern will stop creation of multiple object in multiple thread execution environment. So now complete code will look like below.

        public sealed class LogWriter
        {
            public static LogWriter _Logger;
            private static readonly object obj = new object();
            private LogWriter()
            {
            }
            public static LogWriter Logger
            {
                get
                {
                    if (_Logger == null)
                    {
                        lock (obj)
                        {
                            if (_Logger == null)
                                _Logger = new LogWriter();
                        }
                    }
                    return _Logger;
                }
            }
            private string m_exePath = string.Empty;
            public void LogWrite(string logMessage)
            {
                m_exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                try
                {
                    using (StreamWriter w = File.AppendText(m_exePath + "\\" + "log.txt"))
                    {
                        Log(logMessage, w);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            private void Log(string logMessage, TextWriter txtWriter)
            {
                try
                {
                    txtWriter.Write("\r\nLog Entry : ");
                    txtWriter.WriteLine("{0} {1} : {2}", DateTime.Now.ToShortDateString(),
                        DateTime.Now.ToShortTimeString(), logMessage);
                    txtWriter.WriteLine("-------------------------------");
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
    

    Alternate approach For achieving same pattern

    Above code can be replaced with new c# concept Lazy. Lazy is type safe so there will be no issue if multiple thread will be executed.

    Lazy loading pattern will evaluate property when that will be accessed.

        public sealed class LogWriter
        {
            public static readonly Lazy<LogWriter> _Logger=new Lazy<LogWriter>();
            private LogWriter()
            {
            }
            public static LogWriter Logger
            {
                get
                {
                   return _Logger.Value;
                }
            }
            private string m_exePath = string.Empty;
            public void LogWrite(string logMessage)
            {
                m_exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                try
                {
                    using (StreamWriter w = File.AppendText(m_exePath + "\\" + "log.txt"))
                    {
                        Log(logMessage, w);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            private void Log(string logMessage, TextWriter txtWriter)
            {
                try
                {
                    txtWriter.Write("\r\nLog Entry : ");
                    txtWriter.WriteLine("{0} {1} : {2}", DateTime.Now.ToShortDateString(),
                        DateTime.Now.ToShortTimeString(), logMessage);
                    txtWriter.WriteLine("-------------------------------");
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
    

    Which SOLID pattern Singleton Design Pattern violate

    Singleton design pattern violate SRP ( Single Responsibility Principle). Singleton class creating object as well as providing functionality.

    Summary

    Singleton Pattern will always give only one object in every situation for particular class. This pattern is useful for Resource Contention.

    architecture design principle solid
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Next Article Understanding SOLID Design Principles using real objects
    Dhanik Lal Sahni
    • Website
    • Facebook
    • X (Twitter)

    With over 18 years of experience in web-based application development, I specialize in Salesforce technology and its ecosystem. My journey has equipped me with expertise in a diverse range of technologies including .NET, .NET Core, MS Dynamics CRM, Azure, Oracle, and SQL Server. I am dedicated to staying at the forefront of technological advancements and continuously researching new developments in the Salesforce realm. My focus remains on leveraging technology to create innovative solutions that drive business success.

    Related Posts

    By Dhanik Lal Sahni17 Mins Read

    How to Elevate Your Career to Salesforce Architect

    September 8, 2024
    By Dhanik Lal Sahni8 Mins Read

    Understanding the Salesforce Well-Architected Framework to Enhance Business Outcome

    August 25, 2024
    By Dhanik Lal Sahni8 Mins Read

    Streamlining Authentication: Custom Login Flow in Salesforce

    June 2, 2024
    Add A Comment
    Leave A Reply Cancel Reply

    Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
    Featured on Top Salesforce Developer Blog By ApexHours
    Recent Posts
    • How to Build a Generic Modal Window in Lightning Web Component
    • Top 10 Salesforce Flow Features of Salesforce Summer ’25
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    Ranked in Top Salesforce Blog by feedspot.com
    RSS Recent Stories
    • How to Connect Excel to Salesforce to Manage Your Data and Metadata February 9, 2025
    • Difference Between With Security and Without Security in Apex January 2, 2025
    • Top Reasons to Love Salesforce Trailhead: A Comprehensive Guide December 5, 2024
    • How to Utilize Apex Properties in Salesforce November 3, 2024
    • How to Choose Between SOQL and SOSL Queries July 31, 2024
    Archives
    Categories
    Tags
    apex (111) apex code best practice (8) apex rest (11) apex trigger best practices (4) architecture (22) Asynchronous apex (9) AWS (5) batch apex (9) batch processing (4) code optimization (8) code review tools (3) custom metadata types (5) design principle (9) file upload (3) flow (15) future method (4) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (64) lightning-combobox (5) lightning-datatable (10) lightning component (30) Lightning web component (62) lwc (51) named credential (8) news (4) optimize apex code (4) Permission set (4) pmd (3) Queueable (9) rest api (23) S3 Server (4) salesforce (141) salesforce apex (46) salesforce api (4) salesforce api integration (5) Salesforce Interview Question (4) salesforce news (5) salesforce question (5) solid (6) tooling api (5) Winter 20 (8)

    Get our newsletter

    Want the latest from our blog straight to your inbox? Chucks us your detail and get mail when new post is published.
    * indicates required

    Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
    Featured on Top Salesforce Developer Blog By ApexHours
    Recent Posts
    • How to Build a Generic Modal Window in Lightning Web Component
    • Top 10 Salesforce Flow Features of Salesforce Summer ’25
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    Ranked in Top Salesforce Blog by feedspot.com
    RSS Recent Stories
    • How to Connect Excel to Salesforce to Manage Your Data and Metadata February 9, 2025
    • Difference Between With Security and Without Security in Apex January 2, 2025
    • Top Reasons to Love Salesforce Trailhead: A Comprehensive Guide December 5, 2024
    • How to Utilize Apex Properties in Salesforce November 3, 2024
    • How to Choose Between SOQL and SOSL Queries July 31, 2024
    Archives
    Categories
    Tags
    apex (111) apex code best practice (8) apex rest (11) apex trigger best practices (4) architecture (22) Asynchronous apex (9) AWS (5) batch apex (9) batch processing (4) code optimization (8) code review tools (3) custom metadata types (5) design principle (9) file upload (3) flow (15) future method (4) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (64) lightning-combobox (5) lightning-datatable (10) lightning component (30) Lightning web component (62) lwc (51) named credential (8) news (4) optimize apex code (4) Permission set (4) pmd (3) Queueable (9) rest api (23) S3 Server (4) salesforce (141) salesforce apex (46) salesforce api (4) salesforce api integration (5) Salesforce Interview Question (4) salesforce news (5) salesforce question (5) solid (6) tooling api (5) Winter 20 (8)

    Get our newsletter

    Want the latest from our blog straight to your inbox? Chucks us your detail and get mail when new post is published.
    * indicates required

    Facebook X (Twitter) Instagram Pinterest YouTube Tumblr LinkedIn Reddit Telegram
    © 2025 SalesforceCodex.com. Designed by Vagmine Cloud Solution.

    Type above and press Enter to search. Press Esc to cancel.

    Ad Blocker Enabled!
    Ad Blocker Enabled!
    Our website is made possible by displaying online advertisements to our visitors. Please support us by disabling your Ad Blocker.