Now first I want to mention that I am not quite sure what is the term describing the issue at hand but I hope that I can illustrate it with some code.
Problem: A shared class library defines an Interface and each Application referencing this library provides its own implementation of that interface. Now inside the shared library, I want to call the actual implementation of that method.
Trying to solve this problem I imagined a simple scenario where 2 platform specific applications Windows, Android share some code except for some platform-specific functions that need to be implemented separately for each system. At runtime, I need to transparently call that implementation knowing that it's already provided by the implementer.
Three Console Applications are created Shared, Windows, Android
Shared Project defines an Interface IShared
namespace Project
{
public interface IShared
{
void Speak(string word);
}
}
Android Implements IShared
namespace Project.Android
{
public class SpeakAndroid: IShared
{
public void Speak(string word)
{
Console.WriteLine("Android Speaks");
}
}
}
Windows Implements IShared
namespace Project.Windows
{
public class SpeakWindows: IShared
{
public void Speak(string word)
{
Console.WriteLine("Speak Windows");
}
}
}
Now in order for the Shared project to be able to call each platform specific Speak
function, I decided to declare a
public static IShared SharedDefinition { get; set; }
to which I assign a new Implementation inside Windows and Android projects like so
Windows:
Project.Program.SharedDefinition = new SpeakWindows();
Anrdoid:
Project.Program.SharedDefinition = new SpeakAndroid();
This way in the Shared project I can call Program.SharedDefinition.Speak();
and depending on the running platform i will get different Implementations of Speak
.
Question(s):
- Is this a correct way of solving the above problem? does Service Locator Pattern has anything to do with this?
- For further reading, does the problem above have a name or pattern that best deals with it?