Some times we want to do something when a specific event occurs, for that we can use a callback as I will show next. For me this implementation was realy important to solve a problem, I had a Library so the code will be closed (can't be changed), but I wanted to provide a way to allow extra operations when some event occurs, that was the solution that I had found.
Lets imagine that the next code from SmartHouse.cs and ISmartHouseOperations.cs is closed.
SmartHouse.cs
class SmartHouse
{
ISmartHouseOperations myInterface;
public SmartHouse(ISmartHouseOperations interfaceTest)
{
myInterface = interfaceTest;
}
public void PlaySong(string music) {
/*
* TODO
* Code to play de song
*/
myInterface.PlayMusicEvent(music);
}
public void ChangeLightsState(bool isOn)
{
/*
* TODO
* Code to change the light state
*/
myInterface.TurnLightsEvent(isOn);
}
}ISmartHouseOperations.cs
interface ISmartHouseOperations
{
void PlayMusic(string music);
void TurnLights(bool isOn);
}To define the callbacks, we have to create a class that implements the interface ISmartHouseOperations, so that we can define what to do when a specific operation occurs.
MyHouseEvents.cs
class MyHouseEvents : ISmartHouseOperations
{
public MyHouseEvents() { }
public void PlayMusicEvent(string music)
{
Console.WriteLine("Playing " + music);
}
public void TurnLightsEvent(bool isOn)
{
if (isOn) {
Console.WriteLine("Lights ON");
}
else
{
Console.WriteLine("Lights OFF");
}
}
}Now when a SmartHouse is created we have to specify an object that implements ISmartHouseOperations, so an instance of our MyHouseEvents.cs and then we can call the methods from the SmartHouse.
Program.cs
class Program
{
static void Main(string[] args)
{
Console.WriteLine("CALLBACK IMPLEMENTED WITH INTERFACES");
SmartHouse house = new SmartHouse(new MyHouseEvents());
house.PlaySong("Beethoven - Fur Elise");
house.ChangeLightsState(true);
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}CALLBACK IMPLEMENTED WITH INTERFACES Playing Beethoven - Fur Elise Lights ON Press any key to exit...