设计模式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模式实例.Model;
using MVC模式实例.MyEnum;namespace MVC模式实例.View
{public partial class ViewStudent : Form{private StudentController _controller;public ViewStudent(){InitializeComponent();_controller = new StudentController(this, new StudentModel());EventHandler click = (s, a) => CalculateEventArgs(s);btn_Add.Click += click;btn_Remove.Click += click;btn_RemoveName.Click += click;btn_Updata.Click += click;btn_Query.Click += click;}public bool GetInfo(out object id, out object name, out object age){id = null;name = null;age = null;if (dataGridView1.CurrentCell != null){int index = dataGridView1.CurrentCell.RowIndex;id = dataGridView1.Rows[index].Cells["ID"].Value;name = dataGridView1.Rows[index].Cells["姓名"].Value;age = dataGridView1.Rows[index].Cells["年龄"].Value;return true;}else{MessageBox.Show("请选择数据!");}return false;}private void CalculateEventArgs(object sender){if (sender == btn_Add){_controller.Add();}else if (sender == btn_Remove){_controller.Remove(ERemove.ID);}else if (sender == btn_RemoveName){_controller.Remove(ERemove.Name);}else if (sender == btn_Updata){_controller.Updata();}else if (sender == btn_Query){_controller.Query();}}public void DisplayResult(DataTable table){dataGridView1.DataSource = table;}}}
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();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;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using MVC模式实例.DS;
using MVC模式实例.Extension;
using MVC模式实例.MyEnum;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){Console.WriteLine(CachedDescriptionHelper.GetPropertyDescription<ERemove>(nameof(ERemove.ID)));Console.WriteLine(CachedDescriptionHelper.GetPropertyDescription<ERemove>(nameof(ERemove.Name)));if (index == -1) return;var student = _studentList[index];if (MessageBox.Show($"确认删除信息?" +$"\r\n【{CachedDescriptionHelper.GetPropertyDescription<Student>(nameof(Student.Name))} = {student.Name},年龄 = {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;}if (MessageBox.Show($"修改" + $"\r\n【姓名 = {oldStu.Name},年龄 = {oldStu.Age}】" +$"的信息为:" + $"\r\n【姓名 = {newStu.Name},年龄 = {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(){DataTable dt = new DataTable();dt.Columns.Add("ID");dt.Columns.Add("姓名");dt.Columns.Add("年龄");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;}public void 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));_view.DisplayResult(_model.Query());}public void Remove(ERemove type){var ret = _view.GetInfo(out var id, out var name, out var age);if (!ret) return;if (type == ERemove.ID){_model.RemoveID(long.Parse(id.ToString()));_view.DisplayResult(_model.Query());}else{int.TryParse(age.ToString(), out var nAge);Student student = new Student(-1, name.ToString(), nAge);_model.Remove(student);_view.DisplayResult(_model.Query());}}public void Updata(){var ret1 = _view.GetInfo(out var id, out var name, out var age);if (!ret1) return;FrmUpdataStudent dialog = new FrmUpdataStudent(id, name, age);var ret = dialog.ShowDialog();if (ret == DialogResult.OK){Student oldStu = new Student(long.Parse(id.ToString()), name.ToString(), int.Parse(age.ToString()));Student newStu = dialog.Student;_model.Updata(oldStu, newStu);_view.DisplayResult(_model.Query());}}public void Query(){_view.DisplayResult(_model.Query());}}
}
4.数据结构
using System.ComponentModel;namespace MVC模式实例.DS
{public class Student{[Description("学生的唯一标识符")]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;}}
}
5枚举类型
using System.ComponentModel;namespace MVC模式实例.MyEnum
{/// <summary>/// 删除操作/// </summary>public enum ERemove{[Description("通过ID删除")]ID,[Description("通过姓名删除")]Name}
}
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;}}
}