Unity3D架构之第一弹 《善用接口》

最近好久没有认真的写过博客啦,此时不知为何突然有此意,暂且将原因归为刚看过的一篇微信吧,,,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后


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值