Developer Geeks Home

Implementing Broadcaster class and IListener interface in WinForm

RSS
 

  • Posted one year ago
  • Category: .Net Framework, C#, WinForms,
  • Audiences: Architect, Developer, Web Developer,

This article demostrates how to centralize the sharing of information between objects and the GUI using the Broadcaster class and the IListener interface in WinForms.

Introduction

The Broadcaster class and the IListener interface are used to centralize the sharing of information between objects and the GUI in WinForms. Based on the implementation of the Broadcaster, any class that implements IListener and registers with the Broadcaster is capable of receiving string data sent to the Broadcaster. The following implementation of the Broadcaster class and the IListener interface will demonstrate this method.

Implementation

The Broadcaster class and the IListener interface:

using System;
using System.Collections;

namespace Sample
{
    public interface IListener
    {
        bool Listening();
        void Listen(string message);
    }

    public class Broadcaster
    {
        private static Broadcaster instance = null;
        private ArrayList listeners = null;
        protected Broadcaster()
        {
            listeners = new ArrayList();
        }

        static private Broadcaster Instance
        {
            get
            {
                if (instance == null)
                    instance = new Broadcaster();
                return instance;
            }
        }

        public static void Add(IListener listener)
        {
            Instance.listeners.Add(listener);
        }

        public static void Remove(IListener listener)
        {
            Instance.listeners.Remove(listener);
        }

        public static void Broadcast(string message)
        {
            IEnumerator enumerator = Instance.listeners.GetEnumerator();
            while (enumerator.MoveNext())
            {
                if (((IListener)enumerator.Current).Listening())
                    ((IListener)enumerator.Current).Listen(message);
            }
        }
    }
}

Using the Broadcaster class and the IListener interface from above in a WinForm:

public class FormMain : System.Windows.Forms.Form, IListener
{
    private void FormMain_Load(object sender, System.EventArgs e)
    {
        Broadcaster.Add(this);
    }
    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (components != null)
            {
                components.Dispose();
            }
        }
        Broadcaster.Remove(this);
        base.Dispose(disposing);
    }
    void IListener.Listen(string message)
    {
        ChangeStatus(message.Trim());
    }
    bool IListener.Listening()
    {
        return true;
    }
}

 

comments powered by Developer Geeks

My Recent Articles [13]