设计模式Demo——MVC
- 1.View
- 1.1页面示例
- 1.2View代码
- 1.3修改界面以及代码
- 2.Model
- 3.Controller
- 4.数据结构
- 5.枚举类型
- 6.工具类
- 6.1缓存信息
- 6.2扩展类.
文件结构图
1.View
1.1页面示例
1.2View代码
using System;
using System.Data;
using System.Windows.Forms;
using MVC模式实例.Controller;
using MVC模式实例.DS;
using MVC模式实例.Model;
using MVC模式实例.MyEnum;
namespace MVC模式实例.View
{
public partial class ViewStudent : Form
{
public event EventHandler<EventArgsStudent> EventManage;
public ViewStudent()
{
InitializeComponent();
_ = new StudentController(this, new StudentModel());
}
private void btn_Add_Click(object sender, EventArgs e)
{
EventArgsStudent instance = new EventArgsStudent(EOperation.Add);
EventManage?.Invoke(this, instance);
}
private void btn_Query_Click(object sender, EventArgs e)
{
EventManage?.Invoke(this, new EventArgsStudent(EOperation.Query));
}
private void btn_Updata_Click(object sender, EventArgs e)
{
EventManage?.Invoke(this, CurArgsStudent(EOperation.Updata));
}
private void btn_RemoveName_Click(object sender, EventArgs e)
{
EventManage?.Invoke(this, CurArgsStudent(EOperation.Remove_Nama));
}
private void btn_Remove_Click(object sender, EventArgs e)
{
EventManage?.Invoke(this, CurArgsStudent(EOperation.Remove_Id));
}
private EventArgsStudent CurArgsStudent(EOperation type)
{
EventArgsStudent eventArgsStudent = new EventArgsStudent(type);
if (dataGridView1.CurrentCell != null)
{
int index = dataGridView1.CurrentCell.RowIndex;
Student.GetPropertyName(out string titleId, out string titleName, out string titleAge);
var id = long.Parse(dataGridView1.Rows[index].Cells[titleId].Value.ToString());
var name = dataGridView1.Rows[index].Cells[titleName].Value.ToString();
var age = int.Parse(dataGridView1.Rows[index].Cells[titleAge].Value.ToString());
eventArgsStudent = new EventArgsStudent(type, new Student(id, name, age));
}
else
{
MessageBox.Show("请选择数据!");
}
return eventArgsStudent;
}
public void DisplayResult(DataTable table)
{
dataGridView1.DataSource = table;
}
}
public class EventArgsStudent : EventArgs
{
public EOperation Type { get; set; }
public Student Student { get; set; }
public EventArgsStudent(EOperation type, Student student)
{
Type = type;
Student = student;
}
public EventArgsStudent(EOperation type)
{
Type = type;
}
}
}
1.3修改界面以及代码
using System;
using System.Windows.Forms;
using MVC模式实例.DS;
namespace MVC模式实例.View
{
public partial class FrmUpdataStudent : Form
{
public Student Student => new Student(long.Parse(textBox1.Text), textBox2.Text, int.Parse(textBox3.Text));
public FrmUpdataStudent(object id, object name, object age)
{
InitializeComponent();
Student.GetPropertyName(out string titleId, out string titleName, out string titleAge);
label1.Text = titleId;
label2.Text = titleName;
label3.Text = titleAge;
textBox1.Text = id.ToString();
textBox2.Text = name.ToString();
textBox3.Text = age.ToString();
textBox1.ReadOnly = true;
}
private void button1_Click(object sender, EventArgs e)
{
if (int.TryParse(textBox3.Text, out _))
{
DialogResult = DialogResult.OK;
}
}
}
}
2.Model
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using MVC模式实例.DS;
using MVC模式实例.Extension;
namespace MVC模式实例.Model
{
public class StudentModel
{
private List<Student> _studentList = new List<Student>();
public void Add(Student student)
{
_studentList.Add(student);
}
public void RemoveByIndex(int index)
{
if (index == -1) return;
var student = _studentList[index];
Student.GetPropertyName(out string id, out string name, out string age);
if (MessageBox.Show($"确认删除信息?" +
$"\r\n【{name} = {student.Name},{age} = {student.Age}】", "删除提示", MessageBoxButtons.YesNo) != DialogResult.Yes)
return;
_studentList.RemoveAt(index);
}
public void RemoveID(long id)
{
RemoveByIndex(QueryIndexByID(id));
}
public void Remove(Student student)
{
RemoveByIndex(QueryByNameAge(student.Name, student.Age));
}
public void Updata(Student oldStu, Student newStu)
{
int index = QueryIndexByID(oldStu.ID);
if (index != -1)
{
if (oldStu.Name.Equals(newStu.Name) && oldStu.Age.Equals(newStu.Age))
{
MessageBox.Show("信息内容未修改,无需修改", "提示");
return;
}
Student.GetPropertyName(out string id, out string name, out string age);
if (MessageBox.Show($"修改" + $"\r\n【{name} = {oldStu.Name},{age} = {oldStu.Age}】" +
$"的信息为:" + $"\r\n【{name} = {newStu.Name},{age} = {newStu.Age}】" +
$"", "修改提示", MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
_studentList[index].Name = newStu.Name;
_studentList[index].Age = newStu.Age;
}
}
public Student QueryByID(long id)
{
var index = QueryIndexByID(id);
return index != -1 ? _studentList[index].DeepCopy() : null;
}
public int QueryIndexByID(long id)
{
for (int i = 0; i < _studentList.Count; i++)
{
if (_studentList[i].ID == id)
return i;
}
return -1;
}
public int QueryByNameAge(string name, int age)
{
for (int i = 0; i < _studentList.Count; i++)
{
var t = _studentList[i];
if (t.Name == name && t.Age == age)
return i;
}
return -1;
}
public DataTable Query()
{
Student.GetPropertyName(out string id, out string name, out string age);
DataTable dt = new DataTable();
dt.Columns.Add(id);
dt.Columns.Add(name);
dt.Columns.Add(age);
foreach (var t in _studentList)
{
dt.Rows.Add(t.ID, t.Name, t.Age);
}
return dt;
}
}
}
3.Controller
using System;
using System.Windows.Forms;
using MVC模式实例.DS;
using MVC模式实例.Extension;
using MVC模式实例.Model;
using MVC模式实例.MyEnum;
using MVC模式实例.View;
namespace MVC模式实例.Controller
{
public class StudentController
{
private readonly ViewStudent _view;
private readonly StudentModel _model;
public StudentController(ViewStudent view, StudentModel model)
{
_view = view;
_model = model;
_view.EventManage += OnEventManage;
}
private void OnEventManage(object sender, EventArgsStudent e)
{
switch (e.Type)
{
case EOperation.Add:
Random ran = new Random();
var id = MyExtension.GetTimeLong();
var name = ran.Next(100, 999).ToString();
int age = ran.Next(18, 30);
_model.Add(new Student(id, name, age));
break;
case EOperation.Remove_Id:
_model.RemoveID(e.Student.ID);
break;
case EOperation.Remove_Nama:
_model.Remove(e.Student);
break;
case EOperation.Updata:
FrmUpdataStudent dialog = new FrmUpdataStudent(e.Student);
var ret = dialog.ShowDialog();
if (ret != DialogResult.OK) return;
Student oldStu = e.Student;
Student newStu = dialog.Student;
_model.Updata(oldStu, newStu);
break;
case EOperation.Query:
break;
}
_view.DisplayResult(_model.Query());
}
}
}
4.数据结构
using System.ComponentModel;
using MVC模式实例.Extension;
namespace MVC模式实例.DS
{
public class Student
{
[Description("ID")]
public long ID { get; set; }
[Description("姓名")]
public string Name { get; set; }
[Description("年龄")]
public int Age { get; set; }
public Student(long id, string name, int age)
{
ID = id;
Name = name;
Age = age;
}
public static void GetPropertyName(out string titleId, out string titleName, out string titleAge)
{
titleId = GetPropertyName(nameof(ID));
titleName = GetPropertyName(nameof(Name));
titleAge = GetPropertyName(nameof(Age));
}
public static string GetPropertyName(string propertyName)
{
return CachedDescriptionHelper.GetPropertyDescription<Student>(propertyName);
}
}
}
5.枚举类型
using System.ComponentModel;
namespace MVC模式实例.MyEnum
{
/// <summary>
/// 删除操作
/// </summary>
public enum EOperation
{
[Description("添加数据")]
Add,
[Description("通过ID删除")]
Remove_Id,
[Description("通过姓名删除")]
Remove_Nama,
[Description("修改数据")]
Updata,
[Description("查询数据")]
Query,
}
}
6.工具类
6.1缓存信息
存储枚举、类属性成员的描述信息
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
namespace MVC模式实例.Extension
{
public static class CachedDescriptionHelper
{
private static readonly Dictionary<string, string> descriptionCache = new Dictionary<string, string>();
public static string GetPropertyDescription<T>(string propertyName)
{
string cacheKey = $"{typeof(T).FullName}.{propertyName}";
if (descriptionCache.TryGetValue(cacheKey, out string description))
{
return description;
}
Type type = typeof(T);
PropertyInfo property = type.GetProperty(propertyName);
if (property != null)
{
DescriptionAttribute descriptionAttribute = property.GetCustomAttribute<DescriptionAttribute>();
if (descriptionAttribute != null)
{
description = descriptionAttribute.Description;
descriptionCache[cacheKey] = description;
return description;
}
}
FieldInfo field = type.GetField(propertyName);
if (field != null)
{
DescriptionAttribute descriptionAttribute = field.GetCustomAttribute<DescriptionAttribute>();
if (descriptionAttribute != null)
{
description = descriptionAttribute.Description;
descriptionCache[cacheKey] = description;
return description;
}
}
return null;
}
}
}
6.2扩展类.
用于深度拷贝、获取时间戳。
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace MVC模式实例.Extension
{
/// <summary>
/// 扩展类
/// </summary>
public static class MyExtension
{
/// <summary>
/// 深度拷贝
/// </summary>
public static T DeepCopy<T>(this T obj)
{
if (!obj.GetType().IsSerializable)
{
return default(T);
}
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms, obj);
ms.Position = 0;
return (T)formatter.Deserialize(ms);
}
}
/// <summary>
/// 获取时间戳
/// </summary>
/// <returns></returns>
public static long GetTimeLong()
{
long unixTimestampMs = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds;
return unixTimestampMs;
}
}
}