最近好久没有认真的写过博客啦,此时不知为何突然有此意,暂且将原因归为刚看过的一篇微信吧,,,90后只发说说,不写博客
由于u3d开发和以前写过的.net开发有所不同,以前做.net时会经常用到接口、抽象类,但做u3d后发现,这些很多时候根本不需要,继承了MonoBehaviour的类足可,可能是对设计模式了解得还是过于浅陋吧
所以,今日,我想写篇善用接口,来对游戏架构进行更好的封装隔离,,,
上述是我随便写的一个很简单的例子,项目面板里主要是一个工具类,一个UIIntroView类用于管理IntroView这个UI里的相应模块,UIIntroPresenter类则来管理UIIntroView类,
废话不多说,直接上代码啦
----------Utility.cs----------------------------------------------------------------------------
//一个工具类,用来扩展类的功能
using UnityEngine;
using System.Collections;
public static class GameObjectExtensions
{
public static Interface GetInterface<Interface>(this GameObject go) where Interface : class
{
return go.GetComponent(typeof(Interface)) as Interface;
}
}
----------UIIntroPresenter.cs-------------------------------------------------------------------------
//管理IntroView
using UnityEngine;
using System.Collections;
public class UIIntroPresenter : MonoBehaviour
{
[SerializeField]
GameObject _viewGo = null;
IIntroView _view = null;
void Start()
{
_view = _viewGo.GetInterface<IIntroView>();
test();
}
void test()
{
_view.OpenIntroViewUI();
}
}
----------UIIntroView.cs----------------------------------------------------------------------------
//管理IntroView这个模块,并对外提供处理这个模块的接口
using UnityEngine;
using System.Collections;
public interface IIntroView
{
void OpenIntroViewUI();
}
public class UIIntroView : MonoBehaviour, IIntroView
{
public void OpenIntroViewUI()
{
Debug.LogError("显示IntroView UI");
}
}
到了这,我觉得该说的就已经说完啦
将模块功能封装,仅仅提供接口供外界调节,封装隔离就这样就ok啦
最后再强调一句,我是90后