What is the observer model?
What we always say
- callback
- hook
- listener
- observer
It’s all observer mode…
How does it work?
Take an example! Let’s simulate a scenario — the baby wakes up, the father feeds the baby, the mother holds the baby,
Analysis:
The observer is actually the mom and dad, and the observed is the child.
Are enent events required?
This is still subjective, can be directly written in the kid class, but later change is too troublesome, if the child class is the whole child’s abstract. If you put events in there, it’s ambiguous, not all kids are going to have a particular event, all pulled out, decoupled, semantic.
package observe;
import java.util.ArrayList;
import java.util.List;
/ * * *@authorWu Yang * /
public class Main {
public static void main(String[] args) {
Kids kids = new Kids();
kids.add(new Mom()).add(new Dad());
kids.wakeUp(-1); }}interface Event<T>{}class Kids{
private int degree;
// Upload the object of the child, so that parents can make a judgment based on the child's situation
KidsEvent kidsEvent = new KidsEvent(this);
public int getDegree(a) {
return degree;
}
public void setDegree(int degree) {
this.degree = degree;
}
public boolean isCry(a) {
return isCry;
}
public void setCry(boolean cry) {
isCry = cry;
}
public List<KidsObserve> getList(a) {
return list;
}
public void setList(List<KidsObserve> list) {
this.list = list;
}
private boolean isCry;
// Have a list and iterate through it
private List<KidsObserve>list=new ArrayList<>();
public Kids add(KidsObserve observe){
list.add(observe);
return this;
}
public void wakeUp(int nub){
this.degree=nub;
for(KidsObserve observe:list){ observe.actionWakeUp(kidsEvent); }}}class KidsEvent implements Event<Kids>{
public KidsEvent(Kids kids) {
this.kids = kids;
}
private Kids kids;
public Kids getSource(a){
returnkids; }}interface KidsObserve{
void actionWakeUp(KidsEvent event);
}
class Mom implements KidsObserve{
public void hug(a){
System.out.println("mom");
}
@Override
public void actionWakeUp(KidsEvent event) {
// Events are sometimes required to have kid objects,
Kids source = event.getSource();
int degree = source.getDegree();
if (degree>0){ hug(); }else {
System.out.println("Get Daddy to beat you up."); }}}class Dad implements KidsObserve{
public void feed(a){
System.out.println("dad");
}
@Override
public void actionWakeUp(KidsEvent event) {
// Make choices based on events
Kids source = event.getSource();
int degree = source.getDegree();
// If you cry too much, feed
if (degree>0){
feed();
}else {
System.out.println("gun"); }}}Copy the code