MVC模式实现了职责的分离,便于复用,在不是很复杂的程序中,通常不需要涉及Model部分,下面是一个最简单的计算器的设计. 程序1中业务控制与显示杂糅了,程序2中实现了很好的分离.
程序1:
using System;
class Example
{
static void Main()
{
int x = Convert.ToInt32(Console.ReadLine());
int y = Convert.ToInt32(Console.ReadLine());
int n = x + y;
Console.WriteLine(n);
}
}
程序2:
using System;
class Controller
{
private int x;
private int y;
public int XX
{
set
{
x = value;
}
get
{
return x;
}
}
public int YY
{
set
{
y = value;
}
get
{
return y;
}
}
public int getSum()
{
return x + y;
}
}
class View
{
public string scan()
{
return Console.ReadLine();
}
public void print(int n)
{
Console.WriteLine(n);
}
}
class Example
{
static void Main()
{
View v = new View();
int x = Convert.ToInt32(v.scan());
int y = Convert.ToInt32(v.scan());
Controller c = new Controller();
c.XX = x;
c.YY = y;
int n = c.getSum();
v.print(n);
}
}