什么是MVC?
分为:Model、View、Controller。
交互流程:
View 发起 Controller , Controller 更新 Model 后 刷新 View;
View 可以直接访问 Model。
缺点:Controller 不可复用。
什么是MVP?
多了一层 Presenter ,对 Model 和 View 解耦。
View 发出给 Presenter 事件,Presenter 更新后 Model 刷新 View。
大部分实现的框架都是 MVP 的。
什么是MVVM?
Model、View、ViewModel
Model 还是数据模型。
View 还是视图。
通过 ViewModel 进行数据绑定,更新的 Model 自动刷新到 View。
ViewModel 里面包含几个绑定属性,里面有个事件,用来监听数据更新。
大概如下:
class BindableProperty<T>
{
...
public event Action onValueChanged(T old, T new);
private T _value;
public T Value
{
get
{
return _value;
}
set
{
if (!Equals(_value, value))
{
T old = _value;
_value = value;
this.ValueChanged(old, _value);
}
}
}
}
View 里面有一个 Binder,负责绑定数据到 View 进行监听。
大概如下:
public class UIPropertyBinder<TViewModel>
{
public void Add<TProperty>(string name, Action onValueChanged)
{
FieldInfo fieldInfo = typeof(TData).GetField(name, BindingFlags.Instance | BindingFlags.Public);
if (fieldInfo == null)
{
Debug.LogError(string.Format("Unable to find bindableproperty field '{0}.{1}'", typeof(TData).Name, name));
}
BindableProperty<TProperty> property = this.GetPropertyValue<TProperty>(name, data, fieldInfo);
property.OnValueChanged += onValueChanged;
}
}
这样,再视图调用这个 Binder 的 Add 方法,既可以对数据进行绑定。
当数据更改后,自动触发 onValueChanged 事件,进行自动回调。