Skip to content

Instantly share code, notes, and snippets.

@HamidMolareza
Created December 3, 2024 09:13
Show Gist options
  • Save HamidMolareza/6787e810f9991fc5b16bb6ceb2d81bea to your computer and use it in GitHub Desktop.
Save HamidMolareza/6787e810f9991fc5b16bb6ceb2d81bea to your computer and use it in GitHub Desktop.
Simple factory design pattern in C#
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