상태에 따라 행동이 달라지는 객체를 위한 패턴.
상태에 특화된 행동들을 분리할 수 있고, 새로운 행동을 추가하더라도 다른 행동에 영향을 주지 않음.
public class Client {
public static void main(String[] args) {
Student student = new Student("student");
OnlineCourse onlineCourse = new OnlineCourse();
Student s = new Student("s");
s.addPrivateCourse(onlineCourse);
onlineCourse.addStudent(student);
onlineCourse.changeState(OnlineCourse.State.PRIVATE);
onlineCourse.addStudent(s);
onlineCourse.addReview("hello", student);
}
}
public class Client {
public static void main(String[] args) {
OnlineCourse onlineCourse = new OnlineCourse();
Student student = new Student("student");
onlineCourse.addStudent(student);
onlineCourse.changeState(OnlineCourse.State.PRIVATE);
onlineCourse.addReview("hello", student);
}
}
public class Student {
private String name;
public Student (String anme) {
this.name = name;
}
private Set<OnlineCourse> onlineCourse = new HashSet<>();
public boolean isAvailable (OnlineCourse onlineCourse) {
return onlineCourse.contains(onlineCourse);
}
public void addPrivate(OnlineCourse onlineCourse) {
this.onlineCourses.add(onlineCourse);
}
}
public class OnlineCourse {
private State state;
private List<Student> students;
private List<String> reviews;
public void addStudent(Student student) {
this.state.addStudent(student);
}
public void addReview(String review, Student student) {
this.students.add(student);
if(this.students.size() > 1) {
this.
}
}
}
public class Draft implements State {
private OnlineCourse onlineCourse;
public Draft(OnlineCourse onlineCourse) {
this.onlineCourse = onlineCourse;
}
@Override
public void addReview(String review, Student student) {
throw new UnsupportedOperationException("no review");
}
@Override
public void addStudent(Student student) {
this.onlineCourse.getStudents().add(student);
if(this.onlineCourse.getStudents() > 1) {
this.changeState(new )
}
}
}
public class private implements State {
private OnlineCourse onlineCourse;
public Private(OnlineCourse onlineCourse) {
this.onlineCourse = onlineCourse;
}
@Override
public void addReview(String review, Student student) {
if(this.onlinecourse.getStudents().contains(student)) {
this.onlineCourse.getReviews().add(review);
} else {
throw new UnsupportedOperationException("private");
}
}
@Override
public void addStudent(Student student) {
if(student.isAvailable(this.onlineCourse) {
this.onlineCourse.adStudent(student);
} else {
throw new UnsupportedOperationException("private");
}
}
}
public class Published implements State {
private OnlineCourse onlineCourse;
public Published (OnlineCourse onlinecourse) {
this.onlineCourse = onlineCourse;
}
@Override
public void addReview(String review, String student) {
throw new UnsupportedOperationException ("no draft");
}
@Override
public void addStudent (Student student) {
this.onlineCourse.getStudents().add(studnet);
if(this.onlineCourse.getStudnets().size() > 1) {
this.onlineCourse.changeState(new Private());
}
}
}