C#实现MVC模式简要方法(4)

注意,我们只是有对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();
  }
 }
}

  这里是我们的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来显示编码。
posted on 2009-08-27 22:31  刘宁Toby  阅读(337)  评论(0编辑  收藏  举报