设计模式:策略、模板方法与访问者模式详解
1. 策略模式
策略模式允许定义算法的骨架,然后通过组合来提供与特定策略相关的缺失实现细节。它主要有以下几种实现方式:
- 动态策略 :可以在运行时切换策略。通过 SetOutputFormat() 方法实现策略切换,具体代码如下:
public void SetOutputFormat(OutputFormat format)
{
switch (format) {
case OutputFormat.Markdown:
listStrategy = new MarkdownListStrategy();
break;
case OutputFormat.Html:
listStrategy = new HtmlListStrategy();
break;
default:
throw new ArgumentOutOfRangeException(nameof(format), format, null);
}
}
使用示例:
tp.Clear(); // erases underlying buffer
tp.SetOutputFormat(OutputFormat.Html);
tp.AppendList(new[] { "foo", "bar", "baz" });
WriteLine(tp);
策略、模板与访问者模式解析
超级会员免费看
订阅专栏 解锁全文
1144

被折叠的 条评论
为什么被折叠?



