我正在学习 MVC 模式。我创建了这个非常简单的代码作为演示。
代码的目标很简单。我创建了一个初始速度为每小时 95 英里的汽车对象。有 1 个标签显示当前速度,2 个按钮,增加和减少速度。
单击每个按钮时,速度会增加或减少 1,并且标签会显示修改后的速度。一旦速度超过100,增加按钮被禁用,用户现在只能降低速度。一旦速度降低到 100 以下,增加按钮再次启用。
这是我的模型、视图和控制器的代码。
接口模型
public interface IModel
{
int getCurrentSpeed();
int increaseSpeed();
int decreaseSpeed();
void updateObserver();
void setView(IView objView);
}
类 carModel(来自 IModel 的具体类)
public class carModel : IModel
{
private IView objLocalView;
private int currentSpeed;
//Constructor
public carModel(int carSpeed)
{
this.currentSpeed = carSpeed;
}
public void setView(IView objView)
{
objLocalView = objView;
}
public int increaseSpeed()
{
currentSpeed++;
updateObserver();
return currentSpeed;
}
public int decreaseSpeed()
{
currentSpeed--;
updateObserver();
return currentSpeed;
}
public void updateObserver()
{
objLocalView.updateStatus(this);
}
public int getCurrentSpeed()
{
return currentSpeed;
}
}
接口控制器
public interface IController
{
void requestIncreaseSpeed();
void requestDecreaseSpeed();
}
类 carController(来自 IController 的具体类)
public class carController : IController
{
private IModel objLocalModel;
private IView objLocalView;
//constructor
public carController(IModel objModel, IView objView)
{
objLocalView = objView;
objLocalModel = objModel;
objLocalModel.setView(objView);
}
public void requestIncreaseSpeed()
{
int modifiedSpeed = objLocalModel.increaseSpeed();
checkSpeedLimit(modifiedSpeed);
}
public void requestDecreaseSpeed()
{
int modifiedSpeed = objLocalModel.decreaseSpeed();
checkSpeedLimit(modifiedSpeed);
}
public void checkSpeedLimit(int modifiedSpeed)
{
if (modifiedSpeed > 100)
{
objLocalView.disableIncreaseSpeed();
}
else
{
objLocalView.enableIncreaseSpeed();
}
}
}
界面 IView
public interface IView
{
void enableIncreaseSpeed();
void disableIncreaseSpeed();
void updateStatus(IModel objModel);
}
form1.cs(用户将看到的视图类)
public partial class Form1 : Form, IView
{
private IModel objModel;
private IController objController;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
objModel = new carModel(95);
objController = new carController(objModel, this);
updateStatus(objModel);
}
public void enableIncreaseSpeed()
{
btnIncrease.Enabled = true;
}
public void disableIncreaseSpeed()
{
btnIncrease.Enabled = false;
}
public void updateStatus(IModel objModel)
{
lblCurrentSpeed.Text = "";
lblCurrentSpeed.Text = objModel.getCurrentSpeed().ToString();
}
private void btnIncrease_Click(object sender, EventArgs e)
{
objController.requestIncreaseSpeed();
}
private void btnDecrease_Click(object sender, EventArgs e)
{
objController.requestDecreaseSpeed();
}
}
我不确定这是否是正确的 MVC 设计?因为我看不出与常规 3 层架构有太大区别(除了模型和视图在这里通信,这在 3 层架构中不会发生)