Mediator Design Pattern

Introduction:
Sometimes you want to design your classes set that interact with each other in a loosely coupled manner by keeping your classes away from referring each other directly… Mediator Design Pattern solve this issue by promoting the idea of loosely coupling classes

Example:

MediatorDesignPattern

 

static void Main(string[] args)
{
CountryList countrylist = new CountryList();

CityList city = new CityList();
PhoneNumberTextBox phone = new PhoneNumberTextBox();

countrylist.RegisterMonitorChangers(city);
countrylist.RegisterMonitorChangers(phone);

Console.WriteLine(“——————-“);
countrylist.SelectCountry(“USA”);
Console.WriteLine(“——————-“);
countrylist.SelectCountry(“Jordan”);

Console.ReadKey();

}

abstract class CountryListChangesMonitorBase
{
public CountryList TriggerList { get; set; }

public abstract void RecieveChange(string countryName);
}

class CountryList
{
List<string> countries = new List<string>();
string selectedCountry = “”;

List<CountryListChangesMonitorBase> participants = new List<CountryListChangesMonitorBase>();

public CountryList()
{
countries.Add(“USA”);
countries.Add(“UK”);
countries.Add(“Jordan”);
countries.Add(“Jaban”);
countries.Add(“Germani”);

}

public void SelectCountry(string countryName)
{
if (countries.Contains(countryName))
selectedCountry = countryName;

foreach (CountryListChangesMonitorBase p in participants)
p.RecieveChange(countryName);
}

public void RegisterMonitorChangers( CountryListChangesMonitorBase monitor)
{
if (!participants.Contains(monitor))
participants.Add(monitor);

monitor.TriggerList = this;
}

}

class CityList:CountryListChangesMonitorBase
{
public override void RecieveChange(string countryName)
{
Console.WriteLine(” Display available City List for : ” + countryName);
}
}

class PhoneNumberTextBox: CountryListChangesMonitorBase
{
public override void RecieveChange(string countryName)
{
Console.WriteLine(” Display phone number code for : ” + countryName);
}
}

Download Code

Leave a Reply

Your email address will not be published.