none
Singleton Design Pattern RRS feed

  • General discussion

  • For those who took the link to download ninject let me show you how easy it is to implement the Singleton Design Pattern.

     

    We will have two forms [Form1, Form2]. Form2 will be a Singleton.

     

    We decorate the class with a Singleton attribute, and we are done.

     

    Code Snippet

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using Ninject.Core;

     

    namespace WindowsFormsApplication1
    {
        [Singleton]
        public partial class Form2 : Form
        {
            public Form2()
            {
                InitializeComponent();
            }
        }
    }

     

     

    And here is how we call it. For this small demonstration, I added a public label on Form2 that I will change from Form1.

    Code Snippet

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using Ninject.Core.Activation;

     

    namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {
            private Form2 form2 = Activator.CreateInstance<Form2>();
            public Form1()
            {
                InitializeComponent();
            }

            private void button1_Click(object sender, EventArgs e)
            {          
                form2.Show();
                form2.label1.Text = "Hello forum";
            }       
        }
    }

     

     

    Thursday, July 10, 2008 2:16 AM

All replies