Observer Pattern

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

  1. 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.

  1. 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.

  1. how to implemente it?
observe partern.jpg

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;
    }
}

  1. 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...

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,131评论 0 23
  • 最反感三类人。第一类,自我感觉特别良好总觉得自己超懂得别人想法,明明交集甚少话不过三句但是就是一副自己超成熟超懂得...
    竹里er阅读 311评论 0 0
  • 最普通的奢华是遗忘, 像离别前轻声诉回的四季般漫长。 经铺冗长,用最华丽的词藻, 如何叙写最平凡的糟糠。 年轻人裹...
    爬山猫阅读 1,021评论 97 63
  • 我对自己说,我是唯一的 我也是这么以为的 就是有几个不经意的场景 让一切成为了狗屁 我对自己说 我掌控了朋友圈的目...
    门中人阅读 330评论 0 0