这种设计模式的名称是什么? [英] What's the name of this design pattern?
问题描述
假设我需要将应用程序中的文本保存到文件中,但是允许用户选择多种格式(.pdf
,.word
,.txt
,...
).
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.
第一种方法可能是:
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("...");
}
}
使用它,如果我需要添加新的扩展名/格式,我要做的就是为该编写器创建一个新类(继承自Writer
)并实现CanWriteTo(..)
和Write(..)
方法,并将该新作者添加到WritersHandler
中的作者列表中(也许是添加方法Add(Writer w)
或手动添加,但这不是重点).
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.
我的问题是:
此模式的名称是什么?(也许是对模式的修改,不知道).
What's the name of this pattern? (maybe it's a modification of a pattern, don't know).
推荐答案
我的做法与您有所不同.
I would do it a bit differently than you.
主要区别在于存储处理程序和选择正确处理程序的方式. 实际上,我认为责任链在这里是一个错误的选择.而且,遍历处理程序的ist可能很耗时(如果有更多的处理程序).字典提供O(1)作者检索. 如果我猜到了,我会说我的模式叫做策略.
The main difference would be the way of storing handlers and picking the right one. In fact I think that chain of responsibility is a bad choice here. Moreover iterating through the ist of handlers may be time consuming (if there are more of them). Dictionary provides O(1) writer retrieval. If I were to guess I'd tell that my pattern is called Strategy.
abstract class Writer
{
abstract string SupportedExtension {get;}
abstract void Write(string text, string file);
}
class WritersHandler
{
Dictionary<string,Writer> _writersByExtension = ... //All writers here
public void Init(IEnumerable<Writer> writers)
{
foreach ( var writer in writers )
{
_writersByExtension.Add( writer.SupportedExtension, writer );
}
}
public void Write(string text, string file)
{
Writer w = _writersByExtension.TryGetValue( GetExtension(file) );
if (w == null)
{
throw new Exception("...");
}
w.Write(text, file);
}
}
这篇关于这种设计模式的名称是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!