Mediatorパターン

デザインパターンの本は何冊か読みましたが、いつも途中で飽きてしまい前半で紹介されているパターンしかまともに覚えてなかったりします。(^^;

アジャイルソフトウェア開発の奥義

アジャイルソフトウェア開発の奥義

これは今、読んでいる本。デザパタ本ではありませんがデザインパターンが解説されており、例も簡潔で分かりやすいです。他の本では中盤〜後半にありがちなMediatorパターンが前半にあったので、集中力を持って読めました(笑)。

せっかくなので、本書の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と類似してますね。私はどーにも実装で理解するので、各パターンの区別がつかなくなったりするんですよね。