本文共 2559 字,大约阅读时间需要 8 分钟。
Hi there! today i wanna share something with you, that it is very common and widely used in javascript for example. I'm speaking of callbacks. Do you know how and when this "pattern" is used? Do you really understand it in a java context (environment)? Well i was asking me also some of those questions and that's the reason i started to learn more about it. The ideia behind it is the inversion of control (abbreviated IoC). This paradigma describes the way frameworks work. It is also known as the "Hollywood principle - Don't call me, we will call you"
import java.util.ArrayList;import java.util.List;// For example: Let's assume that this interface is offered from your OS to be implementedinterface TimeUpdaterCallBack { void updateTime(long time);}// this is your implementation.// for example: You want to update your website time every hourclass WebSiteTimeUpdaterCallBack implements TimeUpdaterCallBack { @Override public void updateTime(long time) { // print the updated time anywhere in your website's example System.out.println(time); }}
// This is the SystemTimer implemented by your Operating System (OS)// You don't know how this timer was implemented. This example just// show to you how it could looks like. How you could implement a// callback by yourself if you want to.class SystemTimer { Listcallbacks = new ArrayList (); public void registerCallBackForUpdatesEveryHour(TimeUpdaterCallBack timerCallBack) { callbacks.add(timerCallBack); } // ... This SystemTimer may have more logic here we don't know ... // At some point of the implementaion of this SystemTimer (you don't know) // this method will be called and every registered timerCallBack // will be called. Every registered timerCallBack may have a totally // different implementation of the method updateTime() and my be // used in different ways by different clients. public void oneHourHasBeenExprired() { for (TimeUpdaterCallBack timerCallBack : callbacks) { timerCallBack.updateTime(System.currentTimeMillis()); } }}
/ This is our client. It will be used in our WebSite example. It shall update// the website's time every hour.class WebSiteTimeUpdater { public static void main(String[] args) { SystemTimer SystemTimer = new SystemTimer(); TimeUpdaterCallBack webSiteCallBackUpdater = new WebSiteTimeUpdaterCallBack(); SystemTimer.registerCallBackForUpdatesEveryHour(webSiteCallBackUpdater); }}