Skip to content

Instantly share code, notes, and snippets.

@HamidMolareza
Created December 3, 2024 09:23
Show Gist options
  • Save HamidMolareza/3f344f13f943cfda9ff81625dc2889c8 to your computer and use it in GitHub Desktop.
Save HamidMolareza/3f344f13f943cfda9ff81625dc2889c8 to your computer and use it in GitHub Desktop.
Factory Design Pattern example in C# for exporting Person data to JSON or text formats with flexible factory implementation.
using System.Text.Json;
// Client Code
public static class Program {
public static void Main() {
// 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();
try {
// Use the factory to create the appropriate exporter
var exporter = DataExporterFactory.CreateExporter(format);
// Export the data
var result = exporter.Export(people);
Console.WriteLine(result);
} catch (Exception ex) {
Console.WriteLine($"Error: {ex.Message}");
}
}
}
// Define the Exporter Interface
public interface IDataExporter {
string Export(List<Person> people);
}
// Define the Exporter Factory Interface
public interface IDataExporterFactory {
IDataExporter CreateExporter();
}
// Implement Concrete Exporters
// JSON Exporter
public class JsonDataExporter : IDataExporter {
public string Export(List<Person> people) =>
JsonSerializer.Serialize(people, new JsonSerializerOptions { WriteIndented = true });
}
// JSON Exporter Factory
public class JsonDataExporterFactory : IDataExporterFactory {
public IDataExporter CreateExporter() {
// Simulate complex creation logic for JsonDataExporter
return new JsonDataExporter();
}
}
// Text Exporter
public class TextDataExporter : IDataExporter {
public string Export(List<Person> people) =>
string.Join(Environment.NewLine, people);
}
// Text Exporter Factory
public class TextDataExporterFactory : IDataExporterFactory {
public IDataExporter CreateExporter() {
// Simulate complex creation logic for TextDataExporter
return new TextDataExporter();
}
}
// Create the Abstract Factory
public static class DataExporterFactory {
public static IDataExporter CreateExporter(string? format) {
if (string.IsNullOrWhiteSpace(format)) throw new ArgumentNullException(nameof(format));
IDataExporterFactory factory = format.ToLower() switch {
"json" => new JsonDataExporterFactory(),
"text" => new TextDataExporterFactory(),
_ => throw new ArgumentException("Unsupported export format.")
};
// Use the factory to create the exporter
return factory.CreateExporter();
}
}
// 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