I would like to implement the state pattern in java for the following scenario:
-
The whole story is persisted with EclipseLink
-
A
Personhas aSecurityState(= Security Level). -
Depending on a persons previous
SecurityState, an operationchangeSecurityLevel(and probably other operations too) will have different behaviour.
Person Class
@Entity
public class Person extends DatabaseObject{
// .... lots of properties....
@ManyToOne(fetch=FetchType.LAZY)
private SecurityState securityState;
public changeSecurityState(SecurityState newState){
securityState.changeSecurityState(newState);
}
}
SecurityState:
@Entity
public abstract class SecurityState extends DatabaseObject{
private int level; // 1 = low, 2 = medium, 3 = high
private Person person;
public SecurityState(Person p){
this.person = p;
}
public changeSecurityState(SecurityState newState){
// not implemented
}
public void someOtherOperation(){
}
// getter and setter
}
For example the HighSecurityState:
@Entity
public class HighSecurityState extends SecurityState {
private int level = 3;
public changeSecurityState(SecurityState newState){
if(newState.getLevel() == 1){
// do specific stuff for High-to-Low status changes
person.securityState = new LowSecurityState();
}else if(newState.getLevel() == 2){
person.securityState = new MediumSecurityState();
}else{ }
}
}
Questions: - Is the state-pattern more or less correctly implemented? I don't like the if-else somehow, this doesn't really feel right.
- Which table should be persisted in the database? The abstract
SecurityState? Or the concrete state classes?
Aucun commentaire:
Enregistrer un commentaire