現在我們需要做一些微調使我們的這些接口能夠互相作用。首先,任何一個Control都需要知道它的View和Model,所以在我們的IvehicleControl接口中加入兩個函數:"SetModel" 和"SetVIEw":
public interface IVehicleControl
{
void RequestAccelerate(int paramAmount);
void RequestDecelerate(int paramAmount);
void RequestTurn(RelativeDirection paramDirection);
void SetModel(IVehicleModel paramAuto);
void SetView(IVehicleView paramVIEw);
}
下一個部分比較巧妙。我們希望VIEw知道Model中的變化。為了達到這個目的,我們使用觀察者模式。
注意,我們只是有對IVehicleModel的引用(而不是抽象類Automobile )和對IVehicleView的引用(而不是具體的VIEw),這樣保證對象間的低耦合。
public class AutomobileControl: IVehicleControl
{
private IVehicleModel Model;
private IVehicleView VIEw;
public AutomobileControl(IVehicleModel paramModel, IVehicleView paramVIEw)
{
this.Model = paramModel;
this.View = paramVIEw;
}
public AutomobileControl()
{}
IVehicleControl Members#region IVehicleControl Members
public void SetModel(IVehicleModel paramModel)
{
this.Model = paramModel;
}
public void SetView(IVehicleView paramVIEw)
{
this.View = paramVIEw;
}
public void RequestAccelerate(int paramAmount)
{
if(Model != null)
{
Model.Accelerate(paramAmount);
if(View != null) SetVIEw();
}
}
public void RequestDecelerate(int paramAmount)
{
if(Model != null)
{
Model.Decelerate(paramAmount);
if(View != null) SetVIEw();
}
}
public void RequestTurn(RelativeDirection paramDirection)
{
if(Model != null)
{
Model.Turn(paramDirection);
if(View != null) SetVIEw();
}
}
#endregion
public void SetVIEw()
{
if(Model.Speed > = Model.MaxSpeed)
{
VIEw.DisableAcceleration();
VIEw.EnableDeceleration();
}
else if(Model.Speed <= Model.MaxReverseSpeed)
{
VIEw.DisableDeceleration();
VIEw.EnableAcceleration();
}
else
{
VIEw.EnableAcceleration();
VIEw.EnableDeceleration();
}
if(Model.Speed > = Model.MaxTurnSpeed)
{
VIEw.DisableTurning();
}
else
{
VIEw.EnableTurning();
}
}
}