学校规定,每个学期每位学生最多只能选两门任意公选课,如果低于两门课,学生可以继续选课或者退选已选的课。如果已选两门课,学生只能退选已选的课。请用java代码状态模式模拟学生选课的场景
时间: 2024-05-22 19:14:20 浏览: 200
java代码-使用java解决学生选课系统的源代码
好的,以下是状态模式的Java代码实现:
首先,我们需要定义学生选课的状态接口(State):
public interface State {
void selectCourse();
void dropCourse();
}
然后,我们定义学生选课的三种状态:未选课状态(UnselectedState)、已选一门课程状态(OneCourseState)、已选两门课程状态(TwoCourseState):
public class UnselectedState implements State {
private Student student;
public UnselectedState(Student student) {
this.student = student;
}
@Override
public void selectCourse() {
System.out.println("选了一门课程");
student.setState(student.getOneCourseState());
}
@Override
public void dropCourse() {
System.out.println("不能退选,未选课");
}
}
public class OneCourseState implements State {
private Student student;
public OneCourseState(Student student) {
this.student = student;
}
@Override
public void selectCourse() {
System.out.println("选了第二门课程");
student.setState(student.getTwoCourseState());
}
@Override
public void dropCourse() {
System.out.println("退选了一门课程");
student.setState(student.getUnselectedState());
}
}
public class TwoCourseState implements State {
private Student student;
public TwoCourseState(Student student) {
this.student = student;
}
@Override
public void selectCourse() {
System.out.println("不能再选课程,已选两门");
}
@Override
public void dropCourse() {
System.out.println("退选了一门课程");
student.setState(student.getOneCourseState());
}
}
最后,我们定义学生类(Student):
public class Student {
private State unselectedState;
private State oneCourseState;
private State twoCourseState;
private State currentState;
private int courseCount;
public Student() {
unselectedState = new UnselectedState(this);
oneCourseState = new OneCourseState(this);
twoCourseState = new TwoCourseState(this);
currentState = unselectedState;
courseCount = 0;
}
public void setState(State state) {
currentState = state;
}
public State getUnselectedState() {
return unselectedState;
}
public State getOneCourseState() {
return oneCourseState;
}
public State getTwoCourseState() {
return twoCourseState;
}
public void selectCourse() {
currentState.selectCourse();
courseCount++;
}
public void dropCourse() {
currentState.dropCourse();
courseCount--;
}
}
现在,我们可以创建一个学生对象,然后模拟学生选课的场景:
Student student = new Student();
student.selectCourse(); // 选了一门课程
student.selectCourse(); // 选了第二门课程
student.selectCourse(); // 不能再选课程,已选两门
student.dropCourse(); // 退选了一门课程
student.dropCourse(); // 不能退选,未选课
阅读全文