Created
June 27, 2017 06:20
-
-
Save thenameless314159/cfa8063430994a45033417adc2eb8cc1 to your computer and use it in GitHub Desktop.
Simple FactoryMethod design pattern real-world example
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 LogMessage | |
{ | |
public LogType LogType { get; } | |
public string Message { get; } | |
public string Source { get; } | |
public DateTime Timestamp { get; } | |
public Exception Exception { get; } | |
private LogMessage(LogType logType, string message, string sourceName, Exception exception = null) | |
{ | |
LogType = logType; | |
Message = message; | |
Source = sourceName; | |
Timestamp = DateTime.Now; | |
Exception = exception; | |
} | |
private LogMessage(LogType logType, string message) : this(logType, message, string.Empty) { } | |
public static LogMessage CreateSimple(LogType logType, string message) | |
=> new LogMessage(logType, message); | |
public static LogMessage CreateSimple(LogType logType, string message, string sourceName) | |
=> new LogMessage(logType, message, sourceName); | |
public static LogMessage CreateError(string message, Exception exception) | |
=> new LogMessage(LogType.Error, message, exception.Source, exception); | |
public override string ToString() | |
{ | |
if (Exception != null && !string.IsNullOrEmpty(Source)) | |
return $"[{Timestamp:T}][{LogType}] {Exception.GetType().Name} thrown from {Source}"; | |
return string.IsNullOrEmpty(Source) | |
? $"[{Timestamp:T}][{LogType}] {Message}" | |
: $"[{Timestamp:T}][{LogType}] <{Source}> {Message}"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment