Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A quick example of how abstractions allow runtime substitution
public class Program{
static void Main(string[] args){
ILogger logger;
if(IsUserBirthday())
logger = new BirthdayConsoleLogger();
else
logger = new ConsoleLogger();
// SomethingThatUsesLoggers doesn't care if we're
// logging birthday messages or not, it just
// wants some kind of logger.
var target = new SomethingThatUsesLoggers(logger);
}
bool IsUserBirthday(){
// ... logic for determining birthday ...
return true;
}
}
public class SomethingThatUsesLoggers{
public SomethingThatUsesLoggers(ILogger logger){
logger.Log("Hello from SomethingThatUsesLoggers Constructor!");
}
}
public interface ILogger{
void Log(string message);
}
public class ConsoleLogger : ILogger {
void Log(string message){
Console.WriteLine(message);
}
}
public class BirthdayConsoleLogger : ILogger {
void Log(string message){
Console.WriteLine("A Birthday Message For You: {0}", message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.