Mediatorパターン
デザインパターンの本は何冊か読みましたが、いつも途中で飽きてしまい前半で紹介されているパターンしかまともに覚えてなかったりします。(^^;
- 作者: ロバート・C・マーチン,瀬谷啓介
- 出版社/メーカー: ソフトバンククリエイティブ
- 発売日: 2004/06/30
- メディア: 単行本
- 購入: 3人 クリック: 236回
- この商品を含むブログ (148件) を見る
せっかくなので、本書のJavaコードをC#で書き直してみました。
サンプルは、フォームにはテキストボックスとリストボックスがあり、テキストボックスに入力された文字列で始まっているリストボックスの項目を選択する、というものです。
まずは、Mediator。
using System; using System.Windows.Forms; public class QuickEntryMediator { private TextBox itsTextBox; private ListBox itsListBox; public QuickEntryMediator (TextBox t,ListBox l) { itsTextBox = t; itsListBox = l; itsTextBox.TextChanged += new EventHandler (TextChanged); } void TextChanged (object sender,EventArgs e) { string prefix = itsTextBox.Text; if (prefix == String.Empty) { itsListBox.ClearSelected (); return; } foreach (string s in itsListBox.Items) { if (s.StartsWith (prefix)) { itsListBox.SelectedItem = s; return; } } itsListBox.ClearSelected (); } }
使い方。
using System; using System.Windows.Forms; namespace WindowsApplication5 { public partial class Form1 : Form { public Form1 () { InitializeComponent (); } private void Form1_Load (object sender,EventArgs e) { new QuickEntryMediator (textBox1, listBox1); } } }
このパターンの目的はFacadeと似ていますが、実装はObserverと類似してますね。私はどーにも実装で理解するので、各パターンの区別がつかなくなったりするんですよね。