Command和Service的交互

因为是有关Command和Service的事件,所以将事件枚举命名为

public enum SMCubeEvent {
    GetPositionComplete
}

先看Service层吧

//接口
using strange.extensions.dispatcher.eventdispatcher.api;

public interface IPositionServise  {

    [Inject]
    IEventDispatcher dispatcher { get; set; }

    void GetPosition();
}
//实现
using strange.extensions.context.api;
using strange.extensions.dispatcher.eventdispatcher.api;

public class LinePositionServise : IPositionServise
{
    [Inject]
    public CubePositionModel DataModel { get; set; }

    [Inject]//局部的分发器
    public IEventDispatcher dispatcher { get; set; }

    public void GetPosition()
    {
        //假装是远程获取的数据
        Vector3 pos = new Vector3(Random.Range(0, 2), Random.Range(0, 2), Random.Range(0, 2));

        //保存数据到Model
        DataModel.pos = pos;

        //获取到后通知Command层回调
        dispatcher.Dispatch(SMCubeEvent.GetPositionComplete,pos);
    }
}

然后是Command层

using strange.extensions.command.impl;
using strange.extensions.dispatcher.eventdispatcher.api;

public class CubeInitCommand : EventCommand {

    [Inject]//注入服务层,用来调用事先准备好的接口
    public IPositionServise PositionServise { get; set; }

	public override void Execute ()
	{
        Retain();//保持Command不被销毁,因为服务层获取数据一般都不是立刻的
        PositionServise.dispatcher.AddListener(SMCubeEvent.GetPositionComplete, OnComplete);
        //通过服务层获取数据
        PositionServise.GetPosition();
	}

    private void OnComplete(IEvent evt) {
        dispatcher.RemoveListener(SMCubeEvent.GetPositionComplete, OnComplete);
        //发送命令给Mediator,初始化位置
        dispatcher.Dispatch(MCCubeEvent.InitPositionComplete, (Vector3)evt.data);

        Release();//释放掉,放置内存泄漏
    }
}

总结:这个的交互和View-Mediator有点相像。在Command中获得Service的注入,直接调用接口来交互它,Command中通过注入的Service的局部dispatcher来监听它请求数据的完成回调,当Service层发出相应的请求完成事件,Command中的回调自然被触发。不同的是,因为Service层一般是用来和网络交互的,也就是说它提供的接口是有延迟性的,而Command是完成就会被销毁的,所以要用Retain()来保持Coammand不被销毁,事件完成后在手动销毁Release()。


首页 我的博客
粤ICP备17103704号