Handling Child Object State When It Impacts Parent State
Example:
class Person
{
@OneToMany
List<Action> actionHistory;
@ManyToOne
Employer employer;
private StateEnum myCurrentState = StateEnum.INITIAL_STATE;
}
Imagine a situation like this, where two things are true:
Person.myCurrentState needs to change in reaction to changes in actionHistory, employer, etc. There are a set of business rules like "If action of Type X shows up in action stream and current status is Y then set new status to Z"
Person needs to be able to block and allow some operations on children based on it's current state. For example, it might not be possible to update job title at Employer under certain conditions, or it might not be possible to add Actions meeting certain criteria.
Initially I thought I would just try to funnel all access to children through routines in Person that contain validation/reactionlogic. The result was Person object became too big and all over the place, because of how many operation of children it needed to monitor. (I.e. instead of just getAEmployer(), setNewEmployer() and that kind of thing, it's also things like updateJobTitleAtEmployer(), etc)
Having the logic spread out to the children seems equally messy though. In this case Employer (for example) has to contain tons开发者_如何学运维 of references back to it's parent. Also business rules related to this stuff are scattered all over the place.
Is there any clean general solution to this problem? I'd like some general way that I can have a Parent class vet, and in some cases react to , certain state changes in many of it's children.
UPDATE: I think I mis-used terms "Parent" and "Child" in this question. I'm using them like this: Parent "has a" child/Parent "composed of child". In the example Person would be parent class, and classes of properties would be children.
Better Example:
class Employee
{
private Contract contract;
private List<Action> actions;
private EmployeeState currentState = EmployeeState.INITIAL;
}
Imagine in this case that currentState might change if something in Contract changes (e.g. if rate goes up). It also might be that certain things cannot be set on Contract if Employee is in certain states. In cases where currentState changes, the Contract properties are just one factor in a bigger calculation (i.e. state might be determined by rules like "if Contract.hourlyRate > 30 and actions contains Action with these properties than state is...").
Also, in this case, adding an action might change state of Employee, or be blocked depending on current state.
Is it likely that there's something wrong with my model if I'm running into these problems?
From my understanding, you can use Observer pattern for this kind of situation. In this case, the Contract would subscribe to Employer, so that when the state of the Employer changes, Contract will get notified and it can do its own things based on the current state.
精彩评论