// * model(模型)-表示携带数据的对象。它也可以具有逻辑来更新控制器,如果其数据改变。
public class Employee {
private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
|
// * view(视图)-视图表示模型包含数据的可视化。通常它有UI逻辑
public class EmployeeView {
public void printEmployeeDetails(String name, String no) { System.out.println("Employee:"); System.out.println("Name:" + name); System.out.println("ID" + no); } } |
//* controller(控制器)-控制器引用模型包含的数据的可视化。 //它控制数据流进入模型对象,并在数据更改时更新视图。它保持视图和模型分开。
public class EmployeeController {
private Employee model; private EmployeeView view; public EmployeeController(Employee model,EmployeeView view){ this.model=model; this.view=view; } //设置雇员名称 public void setEmployeeName(String name){ model.setName(name); } //获取雇员名称 public String getEmployeeName(){ return model.getName(); } //设置雇员ID public void setEmployeeId(String rollNo){ model.setId(rollNo); } //获取雇员ID public String getEmployeeId(){ return model.getId(); } //更新视图 模型名称、模型ID public void updateView(){ view.printEmployeeDetails(model.getName(), model.getId()); } }
|
//分别创建对象,打印 更新数据,打印 public class Main {
public static void main(String[] args){ Employee model = new Employee(); model.setName("Tom"); model.setId("1"); EmployeeView view = new EmployeeView(); EmployeeController controller = new EmployeeController(model, view); controller.updateView(); controller.setEmployeeName("New Name"); controller.updateView(); /**Employee: Name:Tom ID1 Employee: Name:New Name ID1 */ } }
|