デザインパターンを覚えたい (Template Method)

Template Methodパターン

共通APIで動作の異なるクラスを作成するためのパターン。
ポイントは

  • 呼び出し元となるテンプレートメソッドは親クラスに実装
  • テンプレートメソッドを構成するメソッドの具体的な定義は子クラスで実装

というところですかね。

なにはともあれ実装。今回は手軽なところでC#にしますか。

まずはC#を実行できる環境をmacに作るためにmonoのSDKを公式サイトから持ってきてインストール。
http://mono-project.com/Main_Page
monoを使う場合のコンパイルと実行は以下のように行う。

$ mcs -out:puni hoge.cs fuga.cs
$ mono puni

あと、emacsにcsharp-modeを突っ込む。
http://www.emacswiki.org/emacs/CSharpMode

書いてみた。C#とか昔少しかじった程度だからすっかり忘れてた。
http://dl.dropbox.com/u/7810000/code/design_pattern/template_method.zip
実行は次の通り。makeだけでテストまで走ります。なお、実行には上で説明したmonoが必要。WindowsならVC#とかでもいけると思う。

$ unzip template_method.zip
$ cd template_method
$ make
mcs -out:template_method_test Main.cs BaseGreeting.cs EnglishGreeting.cs JapaneseGreeting.cs AIGreeting.cs
mono template_method_test
--- English ---
Good morning!
My name is "Hoge"! I'm from the United States of America!
--- Japanese ---
おはよう!
私の名前は"ふが"です! 日本から来ました!
--- AI ---
おはようございます。
独立型戦闘支援ユニット"ADA"です。操作説明を行いますか?