SUPERCAT.DEV

Benvenut* sul mio blog

CSHARP

Design pattern: singleton

14-01-2023

Piccolo recap sui DP

Piccolo esempio chiarificatore

using System;

namespace Singleton
{
    public sealed class Singleton
    {
        private Singleton() { }
        private static Singleton? _instance;

        public static Singleton GetInstance()
        {
            if (_instance is null) _instance = new Singleton();
            return _instance;
        }

        public void Fai()
        {
            // Metodi del singleton
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Singleton a = Singleton.GetInstance();
            Singleton b = Singleton.GetInstance();

            if (a == b) Console.WriteLine("Sono la stessa istanza");
        }
    }
}