Design Patterns

Factory Pattern with example – Exception logger

The intent of Factory Mehod is Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

In below example i have used two different places where exception can be stored – File system and Database. The logs are created depending on the LogType specified by the client.

Create ExceptionFactory.cs class file and add below code.

using System;
namespace dotnetfundamentals.AbstractFactory
{
//Creating the Abstract Logger
public interface ILog
{
void Log();
}
public class FileLogger : ILog
{
public void Log()
{
Console.Write("Log to File");
}
}
public class DBLogger : ILog
{
public void Log()
{
Console.Write("Log to DB");
}
}
//Creating the Concrete Factories
public class LogTypeChecker
{
static public ILog WriteLog(LogType logType)
{
ILog objLog = null;
if(logType == LogType.File)
{
objLog = new FileLogger();
}
else if (logType == LogType.Database)
{
objLog = new DBLogger();
}
return objLog;
}
}
public enum LogType
{
File,
Database
}
}

Add below code in Program.cs file.

using System;
namespace dotnetfundamentals.AbstractFactory
{
class Program
{
static void Main(string[] args)
{
ILog objLogger = LogTypeChecker.WriteLog(LogType.File);
objLogger.Log();
}
}
}

Leave a comment