Command パターン - Wikipedia
どの種類の操作も"操作"とひとくくりにする -> Commandインターフェイス
操作毎に実装クラスを作成する。このクラスに実際の処理を行うクラスを内包する。
下記ソースは
Commandインターフェイスとして「ICommand」
実装コマンドクラスとして「DrawCommand」
そこに内包されている実処理クラスとして「Canvas」
それらを生成・実行・管理するフォームで構成されている。
また、フォームではコマンドを実行順にListへ保存している。
その為、コマンドのUndo処理を行うことができるようになっている。
<summary>
</summary>
public interface ICommand
{
<summary>
</summary>
void execute();
}
<summary>
</summary>
public class DrawCommand : ICommand
{
private IDrawtable drawer = null;
<summary>
</summary>
<param name="drawer"></param>
public DrawCommand(IDrawtable drawer)
{
this.drawer = drawer;
}
<summary>
</summary>
public void execute()
{
drawer.draw();
}
}
<summary>
</summary>
public interface IDrawtable
{
<summary>
</summary>
void draw();
}
<summary>
</summary>
public class Canvas : IDrawtable
{
private Graphics graphics;
private Point pt;
private SolidBrush brush = new SolidBrush(Color.Black);
private Font font = new Font("MS ゴシック", 9f);
private String mark = "●";
<summary>
</summary>
<param name="g"></param>
<param name="pt"></param>
public Canvas(Graphics g, Point pt)
{
this.graphics = g;
this.pt = pt;
}
<summary>
</summary>
public void draw()
{
graphics.DrawString(mark, font, brush, (PointF)pt);
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private Graphics graphics;
private List<ICommand> cmd_history = new List<ICommand>();
private bool is_mouse_down = false;
private int cur_cmd_idx = -1;
private void Form1_Load(object sender, EventArgs e)
{
graphics = panel1.CreateGraphics();
}
private void button1_Click(object sender, EventArgs e)
{
graphics.Clear(Color.White);
cur_cmd_idx = Math.Max(0, cur_cmd_idx - 1);
for (int i = 0; i < cur_cmd_idx; i++)
{
cmd_history[i].execute();
}
}
private void button2_Click(object sender, EventArgs e)
{
cur_cmd_idx = Math.Min(cmd_history.Count - 1, cur_cmd_idx + 1);
cmd_history[cur_cmd_idx].execute();
}
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
is_mouse_down = true;
}
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
if (is_mouse_down == true)
{
Canvas canvas = new Canvas(graphics, e.Location);
DrawCommand cmd = new DrawCommand(canvas);
cmd_history.Add(cmd);
cur_cmd_idx += 1;
canvas.draw();
}
}
private void panel1_MouseUp(object sender, MouseEventArgs e)
{
is_mouse_down = false;
}
private void button3_Click(object sender, EventArgs e)
{
cur_cmd_idx = -1;
cmd_history.Clear();
graphics.Clear(Color.White);
}
}