001package headfirst.combined.djview; 002 003import java.util.ArrayList; 004import java.util.Random; 005 006public class HeartModel implements HeartModelInterface, Runnable { 007 ArrayList<BeatObserver> beatObservers = new ArrayList<BeatObserver>(); 008 ArrayList<BPMObserver> bpmObservers = new ArrayList<BPMObserver>(); 009 int time = 1000; 010 int bpm = 90; 011 Random random = new Random(System.currentTimeMillis()); 012 Thread thread; 013 014 public HeartModel() { 015 thread = new Thread(this); 016 thread.start(); 017 } 018 019 public void run() { 020 int lastrate = -1; 021 022 for(;;) { 023 int change = random.nextInt(10); 024 if (random.nextInt(2) == 0) { 025 change = 0 - change; 026 } 027 int rate = 60000/(time + change); 028 if (rate < 120 && rate > 50) { 029 time += change; 030 notifyBeatObservers(); 031 if (rate != lastrate) { 032 lastrate = rate; 033 notifyBPMObservers(); 034 } 035 } 036 try { 037 Thread.sleep(time); 038 } catch (Exception e) {} 039 } 040 } 041 public int getHeartRate() { 042 return 60000/time; 043 } 044 045 public void registerObserver(BeatObserver o) { 046 beatObservers.add(o); 047 } 048 049 public void removeObserver(BeatObserver o) { 050 int i = beatObservers.indexOf(o); 051 if (i >= 0) { 052 beatObservers.remove(i); 053 } 054 } 055 056 public void notifyBeatObservers() { 057 for(int i = 0; i < beatObservers.size(); i++) { 058 BeatObserver observer = beatObservers.get(i); 059 observer.updateBeat(); 060 } 061 } 062 063 public void registerObserver(BPMObserver o) { 064 bpmObservers.add(o); 065 } 066 067 public void removeObserver(BPMObserver o) { 068 int i = bpmObservers.indexOf(o); 069 if (i >= 0) { 070 bpmObservers.remove(i); 071 } 072 } 073 074 public void notifyBPMObservers() { 075 for(int i = 0; i < bpmObservers.size(); i++) { 076 BPMObserver observer = bpmObservers.get(i); 077 observer.updateBPM(); 078 } 079 } 080}