参考
一、MVC介绍
MVC各层之间关系所对应的设计模式:
View层,单独实现了组合模式
Model层和View层,实现了观察者模式
View层和Controller层,实现了策咯模式
两种MVC框架结构:
1.先按照业务功能划分,再按照MVC划分。这种使得模块更聚焦(高内聚)
2.先按照MVC划分,然后再分出来业务功能
第二种方式用多了发现随着项目的运营模块增多,没有第一种那么好维护。
二、示例
做一个点击按钮切换图片的示例:
Model层
Model_Main.cs :
public class Model_Main : Singleton<Model_Main> //单例
{
public Sprite[] Images = new Sprite[5];
//可添加数据模型变更事件,广播给View层
}
View层
View_Main.cs:
public class View_Main : MonoBehaviour
{
Controller_Main m_ControllerMain; //controller层引用
[HideInInspector]
public Image m_Image;
[HideInInspector]
public Button changeButton;
private void Start()
{
//UI
m_ControllerMain = GameObject.Find("Controller_Main").GetComponent<Controller_Main>();
m_Image = GameObject.Find("MainBg").GetComponent<Image>();
changeButton = GameObject.Find("ChangeButton").GetComponent<Button>();
//调用事件
changeButton.onClick.AddListener(ReplaceImage);
}
private void ReplaceImage()
{
m_ControllerMain.ReplaceImage();
}
}
Controller层
Controller_Main.cs:
public class Controller_Main : MonoBehaviour
{
//view层引用
View_Main m_ViewMain;
private void Awake()
{
//加载资源
for(int i = 0; i < Model_Main.Instance.Images.Length; i ++)
{
Model_Main.Instance.Images[i] = Resources.Load(string.Format("Texture/{0}", i), typeof(Sprite)) as Sprite;
}
m_ViewMain = GameObject.Find("View_Main").GetComponent<View_Main>();
}
//业务功能实现
int i = 0;
public void ReplaceImage()
{
i = ++i % 5;
m_ViewMain.m_Image.overrideSprite = Model_Main.Instance.Images[i];
}
}
总结
Model(数据层):存放静态字段、数据存储、模型资源存储
View(视图层):就是用户可以看到的层,指的是可以看到的UI,模型,加载和调用事件
Controller(管理层):实现业务逻辑功能、加载模型资源、功能实现等