最終更新: yamanobori_old 2010年10月11日(月) 16:51:57履歴
デザインパターン入門
- 中身を変えずに,機能追加ができる.包まれるものを変更することなく,機能の追加を行うことができる.
- 動的な機能追加ができる.クラス間を緩やかに結合している.フレームワークのソースを変更することなく,新しいオブジェクトを作ることができる.
- 単純な品揃えでも,多様な機能追加ができる.
- Decoratorパターンを使うと,よく似ている小さなクラスがたくさん作られてしまうという欠点もある.
// 01_Display.cs namespace chap12 { public abstract class Display { public abstract int getColums(); public abstract int getRows(); public abstract string getRowText(int row); public void show() { for (int i = 0; i < getRows(); i++) { System.Console.WriteLine(getRowText(i)); } } } } // 02_StringDisplay.cs namespace chap12 { class StringDisplay : Display { private string str; public StringDisplay(string str) { this.str = str; } public override int getColums() { return str.Length; } public override int getRows() { return 1; } public override string getRowText(int row) { if (row == 0) return str; else return null; } } } // 03_Border.cs namespace chap12 { public abstract class Border :Display { protected Display display; protected Border(Display display) { this.display = display; } } } // 04_SideBorder.cs namespace chap12 { public class SideBorder : Border { private char borderChar; public SideBorder(Display display, char ch) : base(display) { this.borderChar = ch; } public override int getColums() { return 1 + display.getColums() + 1; } public override int getRows() { return display.getRows(); } public override string getRowText(int row) { return borderChar + display.getRowText(row) + borderChar; } } } // 05_FullBorder.cs namespace chap12 { public class FullBorder : Border { public FullBorder(Display display) : base(display) { } public override int getColums() { return 1 + display.getColums() + 1; } public override int getRows() { return 1 + display.getRows() + 1; } public override string getRowText(int row) { if (row == 0) return "+" + makeLine('-', display.getColums()) + "+"; else if (row == display.getRows() + 1) return "+" + makeLine('-', display.getColums()) + "+"; else return "|" + display.getRowText(row - 1) + "|"; } private string makeLine(char ch, int count) { System.Text.StringBuilder buf = new System.Text.StringBuilder(); for (int i = 0; i < count; i++) { buf.Append(ch); } return buf.ToString(); } } } // 06_Program.cs namespace chap12 { class Program { static void Main(string[] args) { Display b1 = new StringDisplay("Hello,world."); Display b2 = new SideBorder(b1, '#'); Display b3 = new FullBorder(b2); b1.show(); b2.show(); b3.show(); Display b4 = new SideBorder( new FullBorder( new FullBorder( new SideBorder( new FullBorder( new StringDisplay("Hi,Kazunori") ), '*' ) ) ), '/' ); b4.show(); System.Console.Read(); } } }デザインパターン入門
このページへのコメント
q2D7Fl Awesome article.Really looking forward to read more. Fantastic.
BNsvGF Thanks for sharing, this is a fantastic blog article. Want more.