물론 익명으로 리스너 인터페이스를 구현하지 않고, 명시적으로 이름을 부여하는것도 가능하다.
위키피디아의 Delegtion pattern을 보면 어떤 패턴인지 쉽개 확인할 수 있을 것이다.
http://en.wikipedia.org/wiki/Delegation_pattern
[설명]
간단히 설명하면 객체 지향 프로그램에서 한 객체가 모든 일을 수행하는 것이 아니라 어떤 일 중 일부를 다른 객체 (helper object)에게 위임하는 패턴이다.
[예 1]
아래 간단한 예를 보면 Main class가 실행되면 Print 객체의 print() 메서드가 실행되지만 실제 구현으로 보면 Print 객체가 하는 것이 아니라 Print 객체의 의 print() 메서드가 RealPrinter의 print() 메서드를 호출하여 일을 위임하고 있다.
class RealPrinter { // the "delegate"
void print() {
System.out.print("something");
}
}
class Printer { // the "delegator"
RealPrinter p = new RealPrinter(); // create the delegate
void print() {
p.print(); // delegation
}
}
public class Main {
// to the outside world it looks like Printer actually prints.
public static void main(String[] args) {
Printer printer = new Printer();
printer.print();
}
}
[예 2]
조금더 복잡한 예를 보면 C 객체를 사용하여 f(), g() 메서드를 사용할 때 C 클래스의 toA(), toB() 메서드를 이용해 위임할 객체를 골라 줄 수 있도록 구현된 것을 볼 수 있다.
interface I {
void f();
void g();
}
class A implements I {
public void f() { System.out.println("A: doing f()"); }
public void g() { System.out.println("A: doing g()"); }
}
class B implements I {
public void f() { System.out.println("B: doing f()"); }
public void g() { System.out.println("B: doing g()"); }
}
class C implements I {
// delegation
I i = new A();
public void f() { i.f(); }
public void g() { i.g(); }
// normal attributes
public void toA() { i = new A(); }
public void toB() { i = new B(); }
}
public class Main {
public static void main(String[] args) {
C c = new C();
c.f(); // output: A: doing f()
c.g(); // output: A: doing g()
c.toB();
c.f(); // output: B: doing f()
c.g(); // output: B: doing g()
}
}
[그럼 어디 쓰냐? ]
아래 블로그에서 자바로 된 코드 부분을 보면 이해할 수 있다.
http://blog.suminb.com/archives/1441
Java
JButton button = new JButton();
button.addMouseListener(new MouseListener() {
public void mousePressed(MouseEvent e) {
System.out.println("Mouse pressed" + e);
}
public void mouseReleased(MouseEvent e) {
System.out.println("Mouse released" + e);
}
public void mouseEntered(MouseEvent e) {
System.out.println("Mouse entered" + e);
}
public void mouseExited(MouseEvent e) {
System.out.println("Mouse exited" + e);
}
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked" + e);
}
});
자바 버튼을 모두 사용해 보았겠지만 만약 두명이 개발한다고 했을 때 디자이너는 버튼의 위치만 잡아서 보여주는 것을 구현해 놓으면 delegate pattern을 사용해 개발자가 버튼의 역할을 구현할 수 있다. 즉, 버튼의 구체적인 역할을 MouseListener에 위임해 둠으로써 어떤 MouseListener를 구현하는가에 따라서 다른 동작을 할 수 있도록 유연해 질 수 있다는 것이다.
'Design pattern' 카테고리의 다른 글
스트래티지 패턴 (strategy pattern) (0) | 2010.11.17 |
---|