Back to list
Views:   7.9K
Replies:  1
Archived

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:
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.
Jan 29, 2012
I post a c# code, where is it?
Jan 29, 2012
Reply 1
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;
        }
    }
}

 
Fabio Silva, Jan 29, 2012


Stay Inspired!
Join other developers and designers who have already signed up for our mailing list.
Terms     Privacy     Licensing       EULA       Sitemap      
© Data & Object Factory, LLC.
Made with    in Austin, Texas.      Vsn 1.3.0