该类的流畅构建器界面MailTemplate
如下所示:
public class MailTemplateBuilder
{
string _body;
string _subject;
string _sender;
public MailTemplateBuilder WithBody(string body)
{
_body = body;
return this;
}
public MailTemplateBuilder WithSubject(string subject)
{
_subject = subject;
return this;
}
public MailTemplateBuilder WithSender(string sender)
{
_sender = sender;
return this;
}
public MailTemplate Build()
{
return new MailTemplate(_sender, _subject, _body);
}
}
用法如下所示:
var template = _builder.WithBody("body")
.WithSubject("subject")
.WithSender("sender")
.Build();
另一种方法是使用扩展方法:
public static class MailTemplateBuilder
{
public static MailTemplate WithBody(this MailTemplate item, string body)
{
item.MailBody = body;
return item;
}
public static MailTemplate WithSubject(this MailTemplate item, string subject)
{
item.MailSubject = subject;
return item;
}
public static MailTemplate WithSender(this MailTemplate item, string sender)
{
item.MailFrom = sender;
return item;
}
}
用法现在看起来像这样:
var template = new MailTemplate().WithBody("body")
.WithSubject("subject")
.WithSender("sender");
请注意:
在这两种情况下,MailTemplate
该类都不会被此流畅接口的代码污染。这将是一个简单的类:
public class MailTemplate
{
public string MailBody { get; set; } = "";
public string Subject { get; set; } = "";
public string MailFrom { get; set; } = "";
}
因此,在您使用任何一种提供的流畅接口创建该实例后,您可以通过访问属性来简单地读取值:
var body = template.MailBody;