模型實作:ACME2000SportsCar
public class ACME2000SportsCar : Automobile
{
public ACME2000SportsCar(string name) : base(250, 40, -20, name) {}
public ACME2000SportsCar(string name, int maxSpeed, int maxTurn, int maxRev)
: base(maxSpeed, maxTurn, maxRev, name) {}
}
AutoView 類別:實作 IVehicleView、持有 Control/Model 參考
public class AutoView : UserControl, IVehicleView
{
private IVehicleControl _control = new AutomobileControl();
private IVehicleModel _model = new ACME2000SportsCar("Speedy");
public AutoView()
{
InitializeComponent();
WireUp(_control, _model);
}
public void WireUp(IVehicleControl ctrl, IVehicleModel mdl)
{
if (_model != null) _model.RemoveObserver(this); // 解除舊觀察
_model = mdl;
_control = ctrl;
_control.SetModel(_model);
_control.SetView(this);
_model.AddObserver(this); // 註冊觀察者
}
}
UI 事件處理:按鈕點擊轉發至控制器
private void btnAccelerate_Click(object s, EventArgs e)
=> _control.RequestAccelerate(int.Parse(txtAmount.Text));
private void btnDecelerate_Click(object s, EventArgs e)
=> _control.RequestDecelerate(int.Parse(txtAmount.Text));
private void btnLeft_Click(object s, EventArgs e)
=> _control.RequestTurn(RelativeDirection.Left);
private void btnRight_Click(object s, EventArgs e)
=> _control.RequestTurn(RelativeDirection.Right);
介面更新邏輯:UpdateInterface
public void UpdateInterface(IVehicleModel auto)
{
lblStatus.Text = $"{auto.Name} heading {auto.Direction} at speed: {auto.Speed}";
pBar.Value = auto.Speed > 0
? auto.Speed * 100 / auto.MaxSpeed
: auto.Speed * 100 / auto.MaxReverseSpeed;
}