I had a service that I was doing a lot of if/else statements so I found that using Strategy Pattern could help me a lot.
I am working with Mongo and I need to store two different models in the database in different collections. These models extends a common that have some similar information. I started deciding in runtime what class it would be used, but right now my code is showing a warning: unchecked call to 'save(T)' as a member of type 'Strategy'
.
Below is the code I'm trying to do. For now, I just added a @SuppressWarnings("unchecked")
and it's working so far, but I'd like to confirm if this might cause problems and what would be a better approach.
Question: How could I fix this?
Code as of now:
interface Strategy<T extends Person> {
T save(T model);
//other methods
}
class StudentStrategy implements Strategy<Student> {
private StudentRepository studentRepository;
public Student save(Student student) {
return studentRepository.save(student);
}
}
class TeacherStrategy implements Strategy<Teacher> {
private TeacherRepository teacherRepository;
public Teacher save(Teacher teacher) {
return teacherRepository.save(teacher);
}
}
class PersonService {
void doSomething(Person person) {
Strategy strategy = StrategyFactory.getStrategy(person.getType());
strategy.save(person); //THIS LINE SAYS A unchecked call to 'save(T)' as a member of type 'Strategy'
}
}
class StrategyFactory {
public static Strategy getStrategy(PersonType personType) {
if(personType == STUDENT) return new StudentStrategy();
if(personType == TEACHER) return new TeacherStrategy();
return null;
}
}
Old Code:
This is the code I was doing previously. As you can see, there are a lot of if/else. Changing the repository to store Person is not an options as I need the information of each sub class..
class OldPersonService {
void doSomething(Person person) {
if(person.getType == STUDENT) {
studentRepository.save(person);
} else {
teacherRepository.save(person);
}
person.setBirthday(new Date());
person.setName("john");
if(person.getType == STUDENT) {
studentRepository.findReferals(person);
} else {
teacherRepository.findReferals(person);
}
}
}