Let's suppose I need to save a text in my application into a file, but allowing the user to have more than one format (.pdf
, .word
, .txt
, ...
) to select.
A first approach could be:
if (extension == ".pdf")
ExportToPdf(file);
else if (extension == ".txt")
ExportToTxt(file);
...
but I usually encapsulate the above like this:
abstract class Writer
{
abstract bool CanWriteTo(string file);
abstract void Write(string text, string file);
}
class WritersHandler
{
List<Writer> _writers = ... //All writers here
public void Write(string text, string file)
{
foreach (var writer in _writers)
{
if (writer.CanWriteTo(file)
{
writer.Write(text, file);
return;
{
}
throw new Exception("...");
}
}
Using it, if I need to add a new extension/format, all I have to do is create a new class (that inherits from Writer
) for that writer and implement the CanWriteTo(..)
and Write(..)
methods, and add that new writer to the list of writers in WritersHandler
(maybe adding a method Add(Writer w)
or manually, but that's not the point now).
I also use this in other situations.
My question is:
What's the name of this pattern? (maybe it's a modification of a pattern, don't know).