不太明白,怎么会只有2个基本方法呢,方法的个数应该取决于业务逻辑
public interface State {
public void startExam(Student stu) throws ExamException;
public void submitExam(Student stu) throws ExamException;
}
//-----------------------------------
public class Student {
private State state;
public void calScore() {
// 计算成绩
}
public void setState(State state) {
}
}
//--------------------------------------
public class StateNotStart implements State {
public void startExam(Student stu) throws ExamException {
synchronized (stu) {
stu.setState(new StateExaming());
}
}
public void submitExam(Student stu) throws ExamException {
throw new ExamException("Wrong State");
}
}
//----------------------------------------
public class StateExaming implements State {
public void startExam(Student stu) throws ExamException {
throw new ExamException("Wrong State");
}
public void submitExam(Student stu) throws ExamException {
synchronized (stu) {
stu.calScore();
stu.setState(new StateFinished());
}
}
}
//-------------------------------
public class StateFinished implements State {
public void startExam(Student stu) throws ExamException {
throw new ExamException("Wrong State");
}
public void submitExam(Student stu) throws ExamException {
throw new ExamException("Wrong State");
}
}
还是State和Student耦合,不过觉得就应该这样的说,期待banq指教