先日の WCF を使った配信のサンプルを、メソッドチェインで書き変えてみました。
まず SyndicationFeed を操作する拡張メソッドを用意。
public static class SyndicationFeedExtensions
{
public static SyndicationFeed WithAuthor(this SyndicationFeed feed, string mailAddress)
{
feed.Authors.Add(new SyndicationPerson(mailAddress));
return feed;
}
public static SyndicationFeed WithCategory(this SyndicationFeed feed, string categoryName)
{
feed.Categories.Add(new SyndicationCategory(categoryName));
return feed;
}
public static SyndicationFeed WithDescription(this SyndicationFeed feed, string description)
{
feed.Description = new TextSyndicationContent(description);
return feed;
}
public static SyndicationFeed WithItem(this SyndicationFeed feed, string title, string content, string uri)
{
IList<SyndicationItem> items = feed.Items as IList<SyndicationItem>;
if (items == null)
{
items = new List<SyndicationItem>();
}
items.Add(new SyndicationItem(title, content, new Uri(uri)));
feed.Items = items;
return feed;
}
}
そして SyndicationFeed のプロパティを操作している箇所と SyndacationItem を作成している箇所を書き変え。
public class MyRss : IMyRss
{
public Rss20FeedFormatter GetFeed()
{
SyndicationFeed feed = NewFeed("Nakamura Blog", "Nakamura .Text Powerd Blog", "http://localhost:8000/MyRss")
.WithAuthor("nakamura@wankuma.com")
.WithCategory("雑記")
.WithDescription("雑記です。")
.WithItem("最初の記事", "最初の記事", "http://localhost:8000/MyRss/Contents/1")
.WithItem("2番目の記事", "2番目の記事", "http://localhost:8000/MyRss/Contents/2")
.WithItem("3番目の記事", "3番目の記事", "http://localhost:8000/MyRss/Contents/3");
return new Rss20FeedFormatter(feed);
}
public SyndicationFeed NewFeed(string title, string description, string uri)
{
SyndicationFeed feed = new SyndicationFeed(title, description, new Uri(uri));
return feed;
}
}
すごくスッキリしましたね。
メソッドチェインは書いていて楽しいです(私だけでしょうか)。