Last active
January 15, 2017 19:48
-
-
Save CopperStarSystems/0ff0bbcf068ecbe2aa8bae75a95b66db to your computer and use it in GitHub Desktop.
A quick example of how abstractions allow runtime substitution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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