简体   繁体   中英

Singleton - I can create multiple instances

I thought the point of a singleton was I could only initialize one instance at a time? If this is correct, then I must have a fault in my C# console application code (see below).

Would some one please be kind enough to inform me if my understanding of a singleton is correct or if there is an error in my code.

using System;
using System.Collections.Generic;
using System.Text;

namespace TestSingleton
{
    class Program
    {
        static void Main(string[] args)
        {
            Singleton t = Singleton.Instance;
            t.MyProperty = "Hi";

            Singleton t2 = Singleton.Instance;
            t2.MyProperty = "Hello";

            if (t.MyProperty != "")
                Console.WriteLine("No");

            if (t2.MyProperty != "")
                Console.WriteLine("No 2");

            Console.ReadKey();
        }
    }

    public sealed class Singleton
    {
        private static readonly Singleton instance = new Singleton();

        public string MyProperty { get; set; }

        private Singleton()
        {}

        static Singleton()
        { }

        public static Singleton Instance { get { return instance; } }
    }
}

Infact you have only one instance here. You get 2 pointers

Singleton t = Singleton.Instance; //FIRST POINTER
t.MyProperty = "Hi";

Singleton t2 = Singleton.Instance; //SECOND POINTER
t2.MyProperty = "Hello";

But they both are pointing to the same memory location.

Try

Console.WriteLine("{0}, {1}", t.MyProperty, t2.MyProperty);

Just tested your code and it gives Hello Hello and not Hi Hello . So you were manipulating the same instance

Actually you have only one instance in your sample program. The variables t1 and t2 point to the very same instance of the object. The object you created is

private static readonly Singleton instance = new Singleton();

And both t1 and t2 point to the same object. As said by someone else in memory there is just one object created.

Your reference to Singleton.Instance; is a reference to Singleton.instance and so a reffence to one single object. There is no creation of a second Singleton object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM