Interface as Callback

호출자(Caller) 피호출자(Callee) 호출하는 것이 아니라 피호출자(Callee) 호출자(Caller) 호출하는 것을 말한다

 

callback 포인터나 핸들러를 넘겨줘서 피호출자(Callee) 호출자(Caller) 호출하는 기법으로 코드 재상용이 가능하고, 비동기적으로 처리할 있으며 함수를 추상화 있기 때문에 UI 비동기 처리 시스템에서 callback 기법을 많이 사용한다.

 

java에서는 Callback메커니즘을 구현하기 위해 Interface 사용한다. Java Interface 이용하여 높은 수준의 층에 정의된 서브루틴(또는 함수) 낮은 수준의 추상화층이 호출할 있도록 구성할 있다. 어떤 함수의 정확한 동작은 낮은 수준의 함수에 넘겨주는 함수 포인터(핸들러) 의해 바뀐다. 이것은 코드 재사용을 하는 매우 강력한 기법이라고 말할 있다.

 

다음예제는TextReceiver 콜백으로 사용할 메소드를 등록하여 Interface 구성하고TickerTape 콜백함수를 구현한다. TextSource에서는 생성자에TextReceiver 레퍼런스를 갖도록 한다.

 

TextReceiver.java

 

package callback;

 

/**

 * Callback 메소드 등록

 *

 * @author Steven J.S Min

 *

 */

public interface TextReceiver {

       public void receiveText(String text);

}

 

TickerTape.java

 

package callback;

 

/**

 * 이것은 Output기기중 하나입니다.

 *

 * @author Steven J.S Min

 *

 */

public class TickerTape implements TextReceiver {

 

       @Override

       public void receiveText(String text) {

              System.out.println("TICKER: " + text);

       }

 

}

 

TextSource.java

 

package callback;

 

/**

 * 이클래스에서 주의해서 봐야할 점은 TextSource 오로지 Output 기기로 주어진 메시지를 출력하는 메소드에만 관심을 갖는 다는

 * 것이다. 어떤 함수의 정확한 동작은 낮은 수준의 함수에 넘겨주는 함수 포인터(핸들러) 의해 바뀐다.

 * 이것은 코드 재사용을 하는 매우 강력한 기법이라고 말할 있다.

 *

 * @author Steven J.S Min

 *

 */

public class TextSource {

       TextReceiver receiver; // Reference to the implemented Interface

 

       TextSource(TextReceiver r) {

              receiver = r;

       }

 

       public void sendText(String s) {

              receiver.receiveText(s);

       }

 

       /**

        * @param args

        */

       public static void main(String[] args) {

 

              // Create a object of the class that implements the interface

              TextReceiver tickerTape = new TickerTape();

 

              // Create a object of the class holding the reference to a interface implementation

              TextSource myCar = new TextSource(tickerTape);

 

              // Send a text message, which is our event.

              myCar.sendText("Hallo");

       }

 

}

 

결과 :

    TICKER: Hallo

 

추가 참조 : Observers and Observables [ http://stevenjsmin.tistory.com/36 ]

Posted by Steven J.S Min
,