Description
this week we have a dojo about Observer Pattern. We have do a footballGame.When game is fininshed, fans and reports need to give reactions about the results.This is the first design pattern I have learned.
Question
- Why this dojo is about Observer Pattern?
Observer pattern is used when there is one-to-many relationship between objects such as if one object is modified, its depenedent objects are to be notified automatically.In this dojo, when the game results modified, fans and reports are notified automatically.So this dojo need to use Observer Pattern.
- How many actor classes observer pattern uses ?
Subject, ConcreteSubject, Observer,ConcreteObserver. Subject, Observer and Client. Subject is an object having methods to attach and detach observers to a client object. We have created an abstract class Observer and a concrete class Subject that is extending class Observer.
- how to implemente it?
Step1: create subject class
public class FootballGame {
private List<Spectator> spectators;
public FootballGame(List<Spectator> spectators) {
if (spectators == null) {
spectators = new ArrayList<>();
}
this.spectators = spectators;
}
public void attach(Spectator spectator) {
spectators.add(spectator);
}
public void notifyAllObservers(String scoringTeam) {
for (Spectator reporter : spectators) {
reporter.reactToGoal(scoringTeam);
}
}
Step 2
Create Observer class. Observer.java
public abstract class Observer {
public String reactToGoal(String scoreTeam);
}
Step3
create a speccify observe
public class Reporter implements Spectator {
public String reactToGoal(String scoringTeam) {
return "GOAL by " + scoringTeam;
}
}
- observer pattern applies?
an abstract model has two aspects, one of which depends on the other; an object change will cause the other one or more objects to change, without knowing how many objects will change; an object must notify other objects , And do not know who these objects are; need to create a trigger chain in the system.
Thinking
Althought, observer pattern is a good way .but I am thinking that
If an observer has a lot of direct and indirect observers, it will take a lot of time to notice all the observers...