unity MVC笔记
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public static class MVC
{
//资源
public static Dictionary<string, Model> Models = new Dictionary<string, Model>(); //名字 -- model
public static Dictionary<string, View> Views = new Dictionary<string, View>(); // 名字 -- view
public static Dictionary<string, Type> CommandMap = new Dictionary<string, Type>(); //事件名字 -- 类型
//注册view
public static void RegisterView(View view) {
//防止view重复注册
if (Views.ContainsKey(view.Name))
{
Views.Remove(view.Name);
}
view.RegisterAttentionEvent();
Views[view.Name] = view;
}
//注册model
public static void RegisterModel(Model model)
{
Models[model.Name] = model;
}
//注册controller
public static void RegisterController(string eventName,Type controllerType)
{
CommandMap[eventName] = controllerType;
}
//获取model
public static T GetModel<T>()
where T:Model
{
foreach (var m in Models.Values) {
if (m is T) {
return (T)m;
}
}
return null;
}
//获取view
public static T GetView<T>()
where T : View
{
foreach (var v in Views.Values)
{
if (v is T)
{
return (T)v;
}
}
return null;
}
//发送事件
public static void SendEvent(string eventName,object data = null) {
//controller执行
if (CommandMap.ContainsKey(eventName)) {
Type t = CommandMap[eventName];
//控制器生成
Controller c = Activator.CreateInstance(t) as Controller;
c.Execute(data );
}
//view处理
foreach (var v in Views.Values) {
if (v.AttentionList.Contains(eventName)) {
//执行
v.HandleEvent(eventName,data);
}
}
}
}
Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public abstract class Model
{
//名字标识
public abstract string Name { get; }
//发送事件
protected void SendEvent(string eventName,object data = null)
{
MVC.SendEvent(eventName,data);
}
}
view
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class View : MonoBehaviour {
//名字标识
public abstract string Name { get; }
//事件关心列表
[HideInInspector]
public List<string> AttentionList = new List<string>();
public virtual void RegisterAttentionEvent() {
}
//处理事件
public abstract void HandleEvent(string name, object data);
//发送事件
protected void SendEvent(string eventName, object data = null)
{
MVC.SendEvent(eventName, data);
}
//获取模型
protected T GetModel<T>()
where T:Model
{
return MVC.GetModel<T>() as T;
}
}
Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public abstract class Controller
{
//执行事件
public abstract void Execute(object data);
//获取模型
protected T GetModel<T>()
where T : Model
{
return MVC.GetModel<T>() as T;
}
//获取视图
protected T GetView<T>()
where T : View
{
return MVC.GetView<T>() as T;
}
//注册模型
protected void RegisterModel(Model model)
{
MVC.RegisterModel(model);
}
//注册视图
protected void RegisterView(View view)
{
MVC.RegisterView(view);
}
//注册controler
protected void RegisterController(string eventName, Type controllerType)
{
MVC.RegisterController(eventName,controllerType);
}
}