Third
party applications are great, and its very often smart to use open source or
buy modules you need before making your own. However a lot of third party
applications do create some problems. One is that prices and functionality can
change and new, better and cheaper products come to surface.
Therefore,
you do not want to be to dependent on these applications, so if you find
another tool that does the same thing even better, you should be able to switch
it out easy. A good way to do this is to create a interface and a factory
pattern, and refer to the interface in your code and let the factory class
decide what tool to use. You can also
use this pattern to ease mocking of objects. And let the factory return a mock
object if you are unit testing.
Example in C#:
using System;
namespace Logger
{
// An interface is created
interface iLog
{
bool Log(string s);
}
//An implementation using enterprise libraries logging
class EntLog : iLog
{
public bool Log(string s)
{
//Implement logic to save to log
return false;
}
}
//An implementation using log4net to save logs.
class log4net : iLog
{
public bool Log(string s)
{
//Implement logic to save to log
return false;
}
}
// A factory class
class LogFactory
{
// Creates an object, of the right type.
public static iLog CreateLog(){
return new log4net();
}
}
class Program
{
static void Main(string[] args)
{
// Get the log object to use.
iLog logger = LogFactory.CreateLog();
//Print the type of logger used
Console.Out.WriteLine(logger.GetType());
// Log a message and write the result
Console.Out.WriteLine(logger.Log("Something is happening"));
Console.ReadKey();
}
}
}
To change
this to use entLog instead of log4net, all you have to do is change the object
created in the logfactory. To add a new
logger, all you have to do is create a new class to implement Ilog and change
the creator to return the new logger. The creator could also have a constructor
that takes an input, so that you can decide in the class using the log what
kind of log you want to use.