Skip to content

Instantly share code, notes, and snippets.

@CopperStarSystems
Last active January 15, 2017 19:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CopperStarSystems/0ff0bbcf068ecbe2aa8bae75a95b66db to your computer and use it in GitHub Desktop.
Save CopperStarSystems/0ff0bbcf068ecbe2aa8bae75a95b66db to your computer and use it in GitHub Desktop.
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