這裡是我們的ACME200SportsCar類(從抽象類Automobile繼承,實現了IVehicleModel接口):
public class ACME2000SportsCar:Automobile
{
public ACME2000SportsCar(string paramName):base(250, 40, -20, paramName){}
public ACME2000SportsCar(string paramName, int paramMaxSpeed, int paramMaxTurnSpeed,
int paramMaxReverseSpeed):
base(paramMaxSpeed, paramMaxTurnSpeed, paramMaxReverseSpeed, paramName){}
}
現在輪到我們的VIEw了...
現在終於開始建立我們MVC最後一個部分了...VIEw!
我們要建立一個AutoView來實現IVehicleView接口。這個AutoVIEw將會有對Control和Model接口的引用。
public class AutoView : System.Windows.Forms.UserControl, IVehicleVIEw
{
private IVehicleControl Control = new ACME.AutomobileControl();
private IVehicleModel Model = new ACME.ACME2000SportsCar("Speedy");
}
我們也需要將所有的東西包裝在UserControl的構造函數中。
public AutoVIEw()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
WireUp(Control, Model);
}
public void WireUp(IVehicleControl paramControl, IVehicleModel paramModel)
{
// If we're switching Models, don't keep watching
// the old one!
if(Model != null)
{
Model.RemoveObserver(this);
}
Model = paramModel;
Control = paramControl;
Control.SetModel(Model);
Control.SetVIEw(this);
Model.AddObserver(this);
}
下面,加入我們的Button和一個label來顯示ACME2000 Sports Car的狀態還有狀態條用來為所有的Buttons來顯示編碼。
private void btnAccelerate_Click(object sender, System.EventArgs e)
{
Control.RequestAccelerate(int.Parse(this.txtAmount.Text));
}
private void btnDecelerate_Click(object sender, System.EventArgs e)
{
Control.RequestDecelerate(int.Parse(this.txtAmount.Text));
}
private void btnLeft_Click(object sender, System.EventArgs e)
{
Control.RequestTurn(RelativeDirection.Left);
}
private void btnRight_Click(object sender, System.EventArgs e)
{
Control.RequestTurn(RelativeDirection.Right);
}
加入一個方法來更新接口...
public void UpdateInterface(IVehicleModel auto)
{
this.label1.Text = auto.Name + " heading " + auto.Direction.ToString() + " at speed: " +
auto.Speed.ToString();
this.pBar.Value = (auto.Speed> 0)? auto.Speed*100/auto.MaxSpeed : auto.Speed*100/auto.MaxReverseSpeed;
}