is this implementation of the Singleton and Object null Patterns Thread Safe?

59 Views Asked by At

Im trying to write a simple code to implement the Singleton and object null patterns. the code should check if the new customer has a name, if yes put it in the real customer, and if not in the fakecustomer. My focus in this question is: Is the Singleton pattern making my code thread safe in this case?

interface Icustomer
    {
        string Name { get; }
        bool IsNull { get; }
    }
    class realcustomer : Icustomer
    {
        public string Name { get; set; }
        public bool IsNull { get { return false; } }

        public realcustomer(string name)
        {
            Name = name;
        }
    }
    class fakecustomer : Icustomer
    {
        public string Name { get { return "customer not available"; } }
        public bool IsNull { get { return true; } }

    }
    class checkifnull
    {
        public static Icustomer Getcustomer(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                return new fakecustomer();
            }
            else
            {
                return new realcustomer(name);
            }
        }
    }
    class Singleton
    {
        private int total = 0;

        private static Icustomer cust;

        private Singleton() { }

        public static Icustomer makecust(string name)
        {
            if (cust == null)
            {
                if (string.IsNullOrEmpty(name))
                {
                    cust = new fakecustomer();
                }
                else
                {
                    cust = new realcustomer(name);
                }
                
            }
            return cust;
            
        }

        public void add()
        {
            total++;
        }
        public int getTotal() 
        {
            return total;
        }
    }
    internal class Program
    {
        static void Main(string[] args)
        {
            Icustomer new_cust = Singleton.makecust("name");
        }
    }

each pattern works when implemented on its own, but now i'm trying to use both at the same time.

0

There are 0 best solutions below