Created
December 3, 2024 09:13
-
-
Save HamidMolareza/6787e810f9991fc5b16bb6ceb2d81bea to your computer and use it in GitHub Desktop.
Simple factory design pattern in C#
This file contains hidden or 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
using System.Text.Json; | |
// Client Code | |
public static class Program { | |
public static void Main(string[] args) { | |
// Sample Data | |
var people = new List<Person> { | |
new("John", "Doe"), | |
new("Jane", "Smith"), | |
new("Alice", "Johnson") | |
}; | |
Console.Write("Enter export format (json, text): "); | |
var format = Console.ReadLine(); | |
// Use the factory to create the appropriate exporter | |
var exporter = DataExporterFactory.CreateExporter(format); | |
// Export the data | |
var result = exporter.Export(people); | |
Console.WriteLine(result); | |
} | |
} | |
// Define the Exporter Interface | |
public interface IDataExporter { | |
string Export(List<Person> people); | |
} | |
//Implement Concrete Exporters | |
// JSON Exporter | |
public class JsonDataExporter : IDataExporter { | |
public string Export(List<Person> people) => | |
JsonSerializer.Serialize(people, new JsonSerializerOptions { WriteIndented = true }); | |
} | |
// Text Exporter | |
public class TextDataExporter : IDataExporter { | |
public string Export(List<Person> people) => | |
string.Join(Environment.NewLine, people); | |
} | |
// Create the Factory Class | |
public static class DataExporterFactory { | |
public static IDataExporter CreateExporter(string? format) { | |
if (string.IsNullOrWhiteSpace(format)) throw new ArgumentNullException(nameof(format)); | |
return format.ToLower() switch { | |
"json" => new JsonDataExporter(), | |
"text" => new TextDataExporter(), | |
_ => throw new ArgumentException("Unsupported export format.") | |
}; | |
} | |
} | |
// Define the Person Record | |
public record Person(string Name, string Family) { | |
public override string ToString() { | |
return $"{Name} {Family}"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment