This pattern we use to break the strongly dependency across the class level.
Say, you have Class which does Database operation inside this class you want some logger to perferm like logging the debug message into the flat file.
var log = new Logger();
It is fine up to the day later sometime we have bunch of loggers available like logging Server,console or TCP/IP etc.
Of course we do not want to change all code and replace all lines with
var logger = new Logger();
by
var logger = new TcpLogger();
It is quite good idea to introduce an Interface ILog that is implemented by all the various loggers.
ILog logger = new Logger();
or
ILog logger = new TCPLogger();
or
ILog logger = new ConsoleLogger();
Now the type interface doesn't change type any more, we always keep single interface across.
interface ILog { void Log(string msg); } class Logger : ILog { public void Log(string msg) { //write to file. } } class TCPLogger : ILog { public void Log(string msg) { //write to Server - TCP/IP. } } class ConsoleLogger : ILog { public void Log(string msg) { //write to Console. } } class Database { ILog _ilog; public Database(ILog ilog) { // Dependency Injection. _ilog = ilog; } public void ExecuteNonQuery(string sql) { //do database operaion _ilog.Log("some Database operation happened"); } }
No comments:
Post a Comment