最終更新: yamanobori_old 2011年02月20日(日) 19:37:17履歴
デザインパターン入門
デザインパターン入門
Flyweight役にもたせる情報は,よくよく選ぶ必要があります.
本当に複数箇所に共有させるべき情報だけを,Flyweight役にもたせるのが良いのです.
「色つきの大きな文字列」を使いたいとします.
「色」の情報は,どのクラスにもたせるべきでしょうか?
本当に複数箇所に共有させるべき情報だけを,Flyweight役にもたせるのが良いのです.
「色つきの大きな文字列」を使いたいとします.
「色」の情報は,どのクラスにもたせるべきでしょうか?
- BigCharにもたせる
- BigStringにもたせる
// 01BigChar.cs using System; using System.Text; using System.IO; namespace chap20 { public class BigChar { private char charname; private string fontdata; public BigChar(char charname) { this.charname = charname; StreamReader reader = new StreamReader("..\\..\\" + "big" + charname + ".txt"); string line; try { StringBuilder buf = new StringBuilder(); while ((line = reader.ReadLine()) != null) { buf.AppendLine(line); } reader.Close(); this.fontdata = buf.ToString(); } catch (Exception) { this.fontdata = charname + "?"; } } public void print() { Console.Write(fontdata); } } } // 02BigCharFactory.cs using System.Collections.Generic; namespace chap20 { public class BigCharFactory { private Dictionary<string, BigChar> pool = new Dictionary<string, BigChar>(); private static BigCharFactory singleton = new BigCharFactory(); private BigCharFactory() { } public static BigCharFactory getInstance() { return singleton; } public BigChar getBigchar(char charname) { BigChar bc; if (!pool.TryGetValue("" + charname,out bc)) { bc = new BigChar(charname);//ここでBigCharのインスタンスを生成 pool.Add("" + charname, bc); } return bc; } } } // 03BigString.cs namespace chap20 { public class BigString { private BigChar[] bigchars; public BigString(string str) { bigchars = new BigChar[str.Length]; BigCharFactory factory = BigCharFactory.getInstance(); for (int i = 0; i < bigchars.Length; i++) { bigchars[i] = factory.getBigchar(str[i]); } } public void print() { foreach (BigChar bc in bigchars) { bc.print(); } } } } // 04Program.cs using System; namespace chap20 { public class Program { static void Main(string[] args) { string digit = Console.ReadLine(); if (digit.Length == 0) { } else { BigString bs = new BigString(digit); bs.print(); } Console.ReadKey(); } } }
デザインパターン入門
このページへのコメント
uLPweY I really enjoy the post. Will read on...
6FwhAC Really enjoyed this article post.Really thank you! Will read on...