我想编写一些代码,如果在指定的时间间隔内超过了最大值,则将通知侦听器。
比方说,我想知道某个方法在30秒的滑动时间内调用速度是否太快。
在此方法中,我会通知此watchdog必须增加计数器。
而且我希望能够在配置的时间段内跟踪100个以上的呼叫。
所以看门狗将像这样被实例化:new Watchdog(100, 30, TimeUnit.SECONDS, theListener);
我真的不知道如何开始编码。任何提示将不胜感激。
如果我很了解,您需要一个或几个WatchDog,它们跟踪timeLapse内是否达到了maximumNumber?
我想这很适合观察者模式,在该模式中,主题(例如程序)向观察者发送通知(例如观察狗观察程序的行为)。>>
这里是监视程序正在监视的程序或主题:
public class Subject { private List<WatchDog> watchDogs = new ArrayList<>(); public void add(WatchDog watchDog) { watchDogs.add(watchDog); } public void execute() { for (WatchDog watchDog : watchDogs) { watchDog.update(); } } }
这里是WatchDog的定义:
// Verifies that maxCalls is not reached between lastTimeUpdateWasCalled and // lastTimeUpdateWasCalled + periodInSeconds public class WatchDog { private Date lastTimeUpdateWasCalled = null; private int currentNumberOfCalls = 0; private int maxCalls; private int periodInSeconds; public WatchDog(int maxCalls, int periodInSeconds) { this.maxCalls = maxCalls; this.periodInSeconds = periodInSeconds; } public void update() { this.currentNumberOfCalls = this.currentNumberOfCalls + 1; Date now = new Date(); if (lastTimeUpdateWasCalled == null) { this.lastTimeUpdateWasCalled = now; this.currentNumberOfCalls = 1; return; } long endOfPeriodMillis = lastTimeUpdateWasCalled.getTime() + this.periodInSeconds * 1000L; Date endOfPeriod = new Date(endOfPeriodMillis); if (now.before(endOfPeriod)) { this.currentNumberOfCalls = this.currentNumberOfCalls + 1; if (this.currentNumberOfCalls >= this.maxCalls) { System.out.println("Watchdog has detected that " + this.currentNumberOfCalls + " have been done within " + this.periodInSeconds + " seconds"); } } else { // reinitialization this.currentNumberOfCalls = 1; this.lastTimeUpdateWasCalled = now; } } }
这里是如何将整体组合在一起:
public class Main { public static void main(String[] args) throws Exception { Subject s1 = new Subject(); WatchDog w = new WatchDog(2, 2); s1.add(w); s1.execute(); //Thread.sleep(2000); s1.execute(); } }
有关观察者模式的更多信息,请点击https://sourcemaking.com/design_patterns/observer