Skip to content

Instantly share code, notes, and snippets.

@danielplawgo
Created December 5, 2018 07:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielplawgo/228d3e919ebc7ed16fa8e153f237b08e to your computer and use it in GitHub Desktop.
Save danielplawgo/228d3e919ebc7ed16fa8e153f237b08e to your computer and use it in GitHub Desktop.
Jak zastąpić rozbudowanego switch w aplikacji
public class CsvFormatter : ICsvFormatter
{
public void Export(Report report)
{
Console.WriteLine($"CsvFormatter.Export: {report.Name}");
}
}
public interface ICsvFormatter
{
}
public class CsvFormatter : ICsvFormatter
{
public ExportFormat Format { get; } = ExportFormat.Csv;
public void Export(Report report)
{
Console.WriteLine($"CsvFormatter.Export: {report.Name}");
}
}
public interface ICsvFormatter : IFormatter
{
}
public enum ExportFormat
{
Xml,
Csv
}
public interface IFormatter
{
ExportFormat Format { get; }
void Export(Report report);
}
public class Report
{
public string Name { get; set; }
public ExportFormat ExportFormat { get; set; }
}
public class ReportProcessorWithoutSwitch : IReportProcessor
{
private IEnumerable<IFormatter> _formatters;
public ReportProcessorWithoutSwitch(IEnumerable<IFormatter> formatters)
{
_formatters = formatters;
}
public void Process(Report report)
{
var formatter = _formatters.FirstOrDefault(f => f.Format == report.ExportFormat);
if (formatter == null)
{
throw new Exception("Not supported report formatter.");
}
formatter.Export(report);
}
}
public class ReportProcessorWithSwitch : IReportProcessor
{
private IXmlFormatter _xmlFormatter;
private ICsvFormatter _csvFormatter;
public ReportProcessorWithSwitch(IXmlFormatter xmlFormatter,
ICsvFormatter csvFormatter)
{
_xmlFormatter = xmlFormatter;
_csvFormatter = csvFormatter;
}
public void Process(Report report)
{
switch (report.ExportFormat)
{
case ExportFormat.Xml:
_xmlFormatter.Export(report);
break;
case ExportFormat.Csv:
_csvFormatter.Export(report);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
public class XmlFormatter : IXmlFormatter
{
public void Export(Report report)
{
Console.WriteLine($"XmlFormatter.Export: {report.Name}");
}
}
public interface IXmlFormatter
{
}
public class XmlFormatter : IXmlFormatter
{
public ExportFormat Format { get; } = ExportFormat.Xml;
public void Export(Report report)
{
Console.WriteLine($"XmlFormatter.Export: {report.Name}");
}
}
public interface IXmlFormatter : IFormatter
{
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment