程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> C#實現MVC模式的簡要方法(5)

C#實現MVC模式的簡要方法(5)

編輯:關於C語言

這裡是我們的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;
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved