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

作为总是想的远一点的开发人员,我们想让我们的系统有一个长久并且良好的生命周期。这就是说能够进可能的准备好满足ACME的很多变化。为了做到这一点,我们知道要遵循两条原则...“保证你的类低耦合”,要达到这个目标,还要“对接口编程”。

  所以我们要做三个接口(正如你所猜测,一个Model接口,一个View接口,一个Control接口)。

  经过很多调查研究,和与ACME人的费力咨询,我们得到了很多有关详细设计的信息。我们想确定我们可以设置的最大速度在前进,后退和转弯中。我们也需要能够加速,减速,左转和右转。我们的仪表盘必须显示当前的速度和方向。

  实现所有这些需求是非常苛刻的,但是我们确信我们能够做到...

  首先,我们考虑一下基本的项目。我们需要一些东西来表示方向和转动请求。我们做了两个枚举类型:AbsoluteDirection 和 RelativeDirection。

public enum AbsoluteDirection
{
 North=0, East, South, West
}
public enum RelativeDirection
{
 Right, Left, Back
}

  下面来解决Control接口。我们知道Control需要将请求传递给Model,这些请求包括:Accelerate, Decelerate, 和 Turn。我们建立一个IVehicleControl接口,并加入适当的方法。

public interface IVehicleControl
{
 void Accelerate(int paramAmount);
 void Decelerate(int paramAmount);
 void Turn(RelativeDirection paramDirection);
}

  现在我们来整理Model接口。我们需要知道汽车的名字,速度,最大速度,最大倒退速度,最大转弯速度和方向。我们也需要加速,减速,转弯的函数。

public interface IVehicleModel
{
 string Name{ get; set;}
 int Speed{ get; set;}
 int MaxSpeed{ get;}
 int MaxTurnSpeed{ get;}
 int MaxReverseSpeed { get;}
 AbsoluteDirection Direction{get; set;}
 void Turn(RelativeDirection paramDirection);
 void Accelerate(int paramAmount);
 void Decelerate(int paramAmount);
}

  最后,我们来整理View接口。我们知道View需要暴露出Control的一些机能,比如允许或禁止加速,减速和转弯申请。

public interface IVehicleView
{
 void DisableAcceleration();
 void EnableAcceleration();
 void DisableDeceleration();
 void EnableDeceleration();
 void DisableTurning();
 void EnableTurning();
 }

  现在我们需要做一些微调使我们的这些接口能够互相作用。首先,任何一个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中的变化。为了达到这个目的,我们使用观察者模式。
posted on 2009-08-27 22:29  刘宁Toby  阅读(368)  评论(0编辑  收藏  举报