Home  /  Questions  /  Question



50   50
Jan 29, 2012


Is this a correct implementation of the Singleton Pattern?

Hi!

I don´t programme since year 2005, I am just restarting to program, but now in C# instead of Java.
I think it´s a good idea to start studying the design patterns and I was wondering if I can write my own examples and submit here for correction... May I do it?  If yes, follow my first try below:
 2 comments
 
I post a c# code, where is it? --- Fabio Silva  Jan 29, 2012
 
Fabio, you need to click the Append button, so that the code is 'appended' to your message.. Hope this helps. --- Trey Henlon  Jan 29, 2012



50   50
Jan 29, 2012
Follow the code now... It´s working fine, just need to check if singleton pattern is correct implemented.
Thankyou in advance

using System;
using System.Data.Odbc;

namespace TesteSingleton
{
    class Program
    {
        static void Main(string[] args)
        {

            OdbcConnection cnnn = Conexao.Instancia();
            string sql = "SELECT * FROM dbo.loteria";
            OdbcCommand oc = new OdbcCommand(sql,cnnn);
            
            cnnn.Open();

            OdbcDataReader dataReader1 = oc.ExecuteReader();

            while (dataReader1.Read())
            {
                Console.WriteLine(dataReader1["Concurso"] + " " + dataReader1["DataSorteio"] + "\n");
            }
            dataReader1.Close();
            cnnn.Close();

            Console.ReadLine();

        }
    }
        
    // The singleton class
    class Conexao
    {
        private static OdbcConnection cn;

        protected Conexao() {
        }

        public static OdbcConnection Instancia()
        {
            string dsndatabase = "DSN=Loteria;Database=Loteria";
            if (cn==null)
            {
                cn = new OdbcConnection(dsndatabase);
            }
            return cn;
        }
    }
}