Exemplo n.º 1
0
        public static void Run()
        {
            Singleton s1 = Singleton.Instance();
            Singleton s2 = Singleton.Instance();

            if (s1 == s2)
            {
                Console.WriteLine("Object are of the same instance");
            }

            Console.ReadKey();
        }
Exemplo n.º 2
0
        public static void Test()
        {
            var tasks = new List <Task>();

            for (int i = 0; i < 20; i++)
            {
                tasks.Add(new Task(() =>
                {
                    Singleton singleton = Singleton.Instance();
                    singleton.GetData();
                }));
            }
            //并发执行20个任务
            tasks.AsParallel().ForAll(p => p.Start());
        }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            Console.WriteLine("Singleton Pattern");

            Singleton s1 = Singleton.Instance();
            Singleton s2 = Singleton.Instance();

            // Test for same instance
            if (s1 == s2)
            {
                Console.WriteLine("Objects are the same instance");
            }

            // Wait for user
            Console.ReadKey();
        }
Exemplo n.º 4
0
        public void Start()
        {
            // Constructor is protected -- cannot use new

            Singleton dispatcher1 = Singleton.Instance();

            // We can use singleton objects as parameter
            TaxiMessage(dispatcher1);

            Singleton dispatcher2 = Singleton.Instance();

            BusMessage(dispatcher2);

            // Test for same instance

            if (dispatcher1 == dispatcher2)
            {
                Console.WriteLine("Singleton dispatcer objects are the same instance");
            }

            Console.WriteLine($"Total dispatcher messages: {dispatcher1.NumberOfMessages}");
        }