using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class Model
{
//只读
public abstract string Name { get; }
protected void SendEvent(string eventName, object data = null)
{
MVC.SendEvent(eventName, data);
}
}
2、View(查询状态、
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class View : MonoBehaviour
{
//标识
public abstract string Name { get; }
//事件列表
public List<string> AttationEvents = new List<string>();
//事件处理函数
public abstract void Execeute(object data);
//获取模型
protected Model GetModel<T>()
where T : Model
{
return MVC.GetModel<T>();
}
//发送消息
protected void SendEvent(string eventName, object data = null)
{
MVC.SendEvent(eventName, data);
}
}
3、Controller: 协调Model与View之间的交互
using System.Collections;
using System.Collections.Generic;
using System;
public abstract class Controller
{
//获取模型
protected Model GetModel<T>()
where T : Model
{
return MVC.GetModel<T>();
}
//获取视图
protected View GetView<T>()
where T : View
{
return MVC.GetView<T>();
}
protected void RegisterModel(Model model)
{
MVC.RegisterModel(model);
}
protected void RegisterView(View view)
{
MVC.RegisterView(view);
}
protected void RegisterController(string eventName, Type controllerType)
{
MVC.RegisterController(eventName, controllerType);
}
//处理系统消息
public abstract void Execeute(object data);
}
4、MVC:保存MVC & 处理事件分发
public static class MVC
{
//存储MVC
public static Dictionary<string, Model> Models = new Dictionary<string, Model>(); //名字---模型
public static Dictionary<string, View> Views = new Dictionary<string, View>(); //名字---视图
public static Dictionary<string, Type> CommandMap = new Dictionary<string, Type>(); //事件名字---控制器类型
//注册
public static void RegisterModel(Model model)
{
Models[model.Name] = model;
}
public static void RegisterView(View view)
{
Views[view.Name] = view;
}
public static void RegisterController(string eventName, Type controllerType)
{
CommandMap[eventName] = controllerType;
}
//获取
public static Model GetModel<T>()
where T : Model
{
foreach(Model m in Models.Values)
{
if (m is T)
return m;
}
return null;
}
public static View GetView<T>()
where T : View
{
foreach (View v in Views.Values)
{
if (v is T)
return v;
}
return null;
}
//发送事件
public static void SendEvent(string eventName, object data = null)
{
//控制器响应事件
if (CommandMap.ContainsKey(eventName))
{
Type t = CommandMap[eventName];
Controller c = Activator.CreateInstance(t) as Controller;
//控制器执行
c.Execeute(data);
}
//视图响应事件
foreach (View v in Views.Values)
{
if (v.AttationEvents.Contains(eventName))
{
//视图响应事件
v.Execeute(data);
}
}
}
}