using System;
namespace QFramework.Example
{
public class CounterAppModel : AbstractModel
{
private int mCount
public int Count
{
get => mCount;
set
{
if(mCount != value)
{
mCount = value;
PlayerPrefs.SetInt(nameof(Count),mCount);
}
}
}
protected override void OnInit()
{
var storage = this.GetUtility<Storage>();
Count = storage.LoadInt(nameof(Count));
CountApp.Interface.RegisterEvent<CountChangeEvent>(e =>
{
this.GetUtility<Storage>().SaveInt(nameof(Count), Count);
});
}
}
public class Storage : IUtility
{
public void SaveInt(string key, int value)
{
PlayerPrefs.SetInt(key, value);
}
public int LoadInt(string key, int defaultValue = 0)
{
return PlayerPrefs.GetInt(key, defaultValue);
}
}
public class CounterApp : Architecture<CounterApp>
{
protected override void Init()
{
this.RegisterModel(new CounterAppModel());
this.RegisterUtility(new Storage());
}
}
public struct CountChangeEvent
{
}
public class IncreaseCountCommand : AbstractCommand
{
protected override void OnExecute()
{
this.GetModel<CounterAppModel>().Count++;
this.SendEvent<CountChangeEvent>();
}
}
public class DecreaseCountCommand : AbstractCommand
{
protected override void OnExecute()
{
this.GetModel<CountAppModel>().Count--;
this.SendEvent<CountChangeEvent>();
}
}
public class CounterAppController : MonoBehaviour, IController
{
private Button mBtnAdd;
private Button mBtnSub;
private Text mCountText;
private CounterAppModel mModel;
void Start()
{
mModel = this.GetModel<CounterAppModel>();
mBtnAdd = transform.Find("BtnAdd").GetComponent<Button>();
mBtnSub = transform.Find("BtnSub").GetComponent<Button>();
mCountText = transform.Find("CounterText").GetComponent<Text>();
mBtnAdd.onClick.AddListener(() = >
{
this.SendCommand<IncreaseCountCommand>();
});
mBtnSub.onClick.AddListener(() = >
{
this.SendCommand(new DecreaseCountCommand>());
});
UpdateView();
this.RegisterEvent<CountChangeEvent>(e =>
{
UpdateView();
}).UnRegisterWhenGameObjectDestroyed(gameObject);
}
void UpdateView()
{
mCountText.text = mCount.ToString();
}
public IArchitecture GetArchitecture()
{
return CounterApp.Interface;
}
private void OnDestroy()
{
mModel = null;
}
}
}