StrangeIOC框架 是Unity一个开源的框架,在asset store上可以获取,我们主要是学习它的架构思想,架构如下:
注:本文需对StrangeIOC有一定了解,如注入等;
我们假设要实现一个: 发起游戏结束事件,显示游戏结束面板,更新显示游戏结束信息的这样一个功能,怎么实现呢?
大体结构如下:
1.发起Command事件
2.派发View更新事件给Mediator,并且更新Model类数据
3.Mediator接收事件
4.Mediator将事件信息交给View处理并更新
看代码:
View代码: View代码负责的是显示相关的,获取按钮等也在这处理
public class GameOverView : EventView { Text txt_text; public Button btn_Restart; public void Init() { txt_text = transform.Find("txt_text").GetComponent<Text>(); btn_Restart = transform.Find("btn_Restart").GetComponent<Button>(); } public void SetString(string s) { txt_text.text = s; } }Mediator代码:Mediator可以理解为一个中介,用来跟外界的Command做交互 public class GameOverMediator : EventMediator { [Inject] public GameOverView GameOverView { get; set; } public override void OnRegister() { GameOverView.Init(); GameOverView.btn_Restart.onClick.AddListener(OnRestartClick); dispatcher.AddListener(ViewEvent.GameOver,OnGameOver); } public override void OnRemove() { GameOverView.btn_Restart.onClick.RemoveListener(OnRestartClick); dispatcher.RemoveListener(ViewEvent.GameOver, OnGameOver); } public void OnRestartClick() { Application.LoadLevel(0); } //接收事件进行处理,调用View public void OnGameOver(IEvent e) { GameOverArgs eg = e.data as GameOverArgs; string s = eg.ComputerLeftWin ? " 左电脑 " : ""; string s2 = eg.ComputerRightWin ? " 右电脑 " : ""; string s3 = eg.PlayerWin ? " 你 " : ""; GameOverView.SetString("赢家是: " + s + s2 + s3); } }
Commad代码:用来发起操作,并用来链接各个模块 public class GameOverCommand : EventCommand { [Inject(ContextKeys.CONTEXT_VIEW)] public GameObject GameRoot { get; set; } [Inject] public CardModel CardModel { get; set; } //接收事件处理 public override void Execute() { GameOverArgs e = evt.data as GameOverArgs; CardModel.Shuffle(); Tools.CreateUIPanel(PanelType.GameOverPanel); GameRoot.GetComponent<GameRoot>().StartCoroutine(DelayGameOver(e)); } //派发View事件出去 IEnumerator DelayGameOver(GameOverArgs e) { yield return new WaitForSeconds(0.1f); dispatcher.Dispatch(ViewEvent.GameOver, e); } }
Model: 这里就不上代码了,主要用存储主要游戏数据和数据操作函数,比如整个游戏的模式信息,模式的更改函数等等