本文共 3147 字,大约阅读时间需要 10 分钟。
01.介绍
02.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); }}
using System.Collections;using System.Collections.Generic;using UnityEngine;public abstract class View : MonoBehaviour { //名字标识 public abstract string Name { get; } //事件关心列表 [HideInInspector] public ListAttentionList=new List (); //注册事件 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 () where T:Model { return MVC.GetModel () as T; }}
using System.Collections;using System.Collections.Generic;using UnityEngine;using System.Linq;using System.Text;using System;public abstract class Controller { //执行事件 public abstract void Execute(object data); //获取模型 protected T GetModel() where T:Model { return MVC.GetModel () as T; } //获取视图 protected T GetView () where T:View { return MVC.GetView () 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); }}
using System.Collections;using System.Collections.Generic;using UnityEngine;using System.Linq;using System.Text;using System;public static class MVC{ //资源 public static DictionaryModels=new Dictionary ();//名字 -- model public static Dictionary Views=new Dictionary ();//名字 -- View public static Dictionary CommandMap=new Dictionary ();//事件名字 -- 类型 //注册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 () where T:Model { foreach(var m in Models.Values) { if(m is T) { return (T)m; } } return null; } //获取View public static T GetView () 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); } } }}
转载地址:http://sfrxo.baihongyu.com/