各位大大,小弟最近在學MVC的架構,參考了許多的資料,也實作出了1個VIEW對一個Controller對一個Model,的簡單例子,但問題來了,實際在應用時不可能只有一個VIEW,所以我試著在Controller中加入多個VIEW,想了四天終於寫出來了!但小弟覺得怪怪的請大大指點一下,並且可否針對寫法提供一些改善的方法!謝謝~
//Initial.java
import java.util.*;
public class Initial {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
View v = new View("View");
View2 v2 = new View2("View2");
Model m = new Model();
Controller c = new Controller(m);
c.add(v);
c.add(v2);
v.display();
v2.display();
c.showAryList();
}
}
//Controller.java
import java.util.*;
public class Controller {
// private Viewable v;
private Model m;
private List aryList;
public Controller(Model m) {
// TODO Auto-generated constructor stub
this.m = m;
aryList = new ArrayList();
}
public void add(Viewable v) {
aryList.add(v);
System.out.println(v.getName() + "已被加入!");
v.addController(this);
}
public void removeView(Viewable v) {
aryList.remove(v);
System.out.println(v.getName() + "已被刪除!");
}
public void sumNumber(Viewable v, int N1, int N2) {
if (aryList.contains(v)) {
((Viewable) this.aryList.get(aryList.indexOf(v))).show(this.m
.caculate(N1, N2));
}
removeView(v);
}
public void substractNumber(Viewable v, int N1, int N2) {
if (aryList.contains(v)) {
((Viewable) this.aryList.get(aryList.indexOf(v))).show(this.m
.substract(N1, N2));
}
}
public void showAryList() {
for (int i = 0; i < aryList.size(); i++) {
System.out.println(aryList.get(i).getClass());
}
}
}
//Model.java
public class Model {
public Model() {
// TODO 自動產生建構子 Stub
}
public int caculate(int x, int y) {
return x + y;
}
public int substract(int x, int y) {
return x - y;
}
}
//Viewable.java
public interface Viewable {
// final String name;
public String getName();
public void addController(Controller c);
public void show(int result);
}
//View.java
import java.util.*;
public class View implements Viewable {
private int no1;
private int no2;
private Controller c;
private String name;
public View(String n) {
// TODO Auto-generated constructor stub
this.name = n;
}
public String getName() {
return this.name;
}
public void addController(Controller c) {
this.c = c;
}
public void display() {
Scanner s = new Scanner(System.in);
System.out.print("No 1:");
no1 = s.nextInt();
System.out.print("No 2:");
no2 = s.nextInt();
c.sumNumber(this, no1, no2);
}
public void show(int result) {
System.out.println(no1 + "+" + no2 + "=" + result);
}
}
//View2.java
import java.util.Scanner;
public class View2 implements Viewable {
private int no1;
private int no2;
private Controller c;
private String name;
public View2(String n) {
// TODO 自動產生建構子 Stub
this.name = n;
}
public String getName() {
return this.name;
}
public void addController(Controller c) {
this.c = c;
}
public void show(int result) {
// TODO 自動產生方法 Stub
System.out.println(no1 + "-" + no2 + "=" + result);
}
public void display() {
Scanner s = new Scanner(System.in);
System.out.print("No 1:");
no1 = s.nextInt();
System.out.print("No 2:");
no2 = s.nextInt();
c.substractNumber(this, no1, no2);
}
}