Mementoパターン
Memento パターン - Wikipedia
管理したい情報を表すクラス(Memento)
Mementoクラスを作成するクラス(Originator)
OriginatorからMementoを取得・保管するクラス(Caretaker)
で構成される。
MementoのAPIはOriginatorに対しては全て公開されているのに対して、Caretakerには一部しか公開されない。
これはCaretakerはMementoを保存・参照だけする為である。
具体的には下記に記すが、Mementoと同じNamespaceに属するクラスだけにフルでAPIを公開する手法をとっている。
状態を保存するパターンと記されているが、Mementotの情報の破壊を防ぐパターンな気がする。
using System; using System.Collections.Generic; using System.Text; using System.Drawing; namespace MementoLib { /// <summary> /// カーソル情報(Memento役) /// </summary> /// <remarks> /// <pre> /// <![CDATA[ /// アクセス指定にinternalを指定しているものは別アセンブリからはアクセスができない。 /// このパターンはそこを利用したものである。 /// ]]> /// </pre> /// </remarks> public class CursorInfo { private Point _point; internal CursorInfo(int x, int y) { _point = new Point(x, y); } public Point getPoint() { return _point; } internal void updatePassword(int x, int y) { _point = new Point(x, y); } } /// <summary> /// カーソル情報の生成(Originator役) /// </summary> public class CursorInfoMaker { public CursorInfo getCursorInfo() { Random ram = new Random((int)DateTime.Now.Ticks); return new CursorInfo(ram.Next(0, 100), ram.Next(0, 150)); } } }
using System; using System.Collections.Generic; using System.Text; using System.Drawing; using MementoLib; namespace MementoSample { class Program { /// <summary> /// メイン(Caretaker役) /// </summary> /// <param name="args"></param> static void Main(string[] args) { CursorInfoMaker maker = new CursorInfoMaker(); CursorInfo cursor = maker.getCursorInfo(); Point point = cursor.getPoint(); Console.WriteLine("X:{0},Y:{1}", point.X, point.Y); System.Threading.Thread.Sleep(1000); } } }