Delegation

Delegation Pattern은 μ‰½κ²Œ ν‘œν˜„ν•˜μžλ©΄ μ–΄λ–€ κ°μ²΄μ—μ„œ μΌμ–΄λ‚˜λŠ” μ΄λ²€νŠΈμ— κ΄€ν•œ ν˜Ήμ€ μ–΄λ–€ 객체에 λΏŒλ €μ€„ 데이터에 κ΄€ν•œ μ½”λ“œλ₯Ό λ‹€λ₯Έ κ°μ²΄μ—μ„œ μž‘μ„±ν•΄μ£ΌλŠ” 것을 λ§ν•©λ‹ˆλ‹€. 즉 A객체의 일을 Bκ°μ²΄μ—μ„œ λŒ€μ‹ ν•΄μ£ΌλŠ” 일을 μœ„μž„ν•˜λŠ” ν–‰μœ„μž…λ‹ˆλ‹€.

λ‹€μ‹œλ§ν•˜λ©΄ ν•œ 객체가 λͺ¨λ“  일을 μˆ˜ν–‰ν•˜λŠ” 것이 μ•„λ‹ˆλΌ 일뢀λ₯Ό λ‹€λ₯Έ 객체에 μœ„μž„ν•œλ‹€.

예제1) 데이터λ₯Ό μ €μž₯ν•˜κ³  μ½μ–΄μ˜€λŠ” μž‘μ—…

class Data{
    ...
}
class A{
    Data data = new Data();
    public String getMsg(){
        return data.getMsg();    
    }
}

예제2) Printer

public class RealPrinter{
       public void print(){
        System.out.println("ν”„λ¦°νŠΈ");
    }
}
public class Printer{
    RealPrinter p = new RealPrinter();
    void print(){
        p.print();
    }
}
public class Main{
    public static void main(String[] args){
        Printer printer = new Printer();
        printer.print();
    }
}

Main ν΄λž˜μŠ€μ—μ„œ Printer 객체의 print()κ°€ μ‹€ν–‰λ˜μ§€λ§Œ, μ‹€μ œ κ΅¬ν˜„μ„ 보면 RealPrinter 객체의 print() λ©”μ†Œλ“œλ₯Ό μœ„μž„λ°›μ•„μ„œ μ‹€ν–‰ν•˜κ³  μžˆλ‹€.

예제3)

Interface I{
    void f();
    void g();
}
class A implements I{
    public void f(){
        System.out.println("A f()");
    }
    public void g(){
        System.out.println("A g()");
    }
}
class B implements I{
    public void f(){
        System.out.println("B f()");
    }
    public void g(){
        System.out.println("B g()");
    }
}
class C implements I{
    I i = new A();

    public void f(){
        i.f();
    }
    public void g(){
        i.g();
    }
    public void toA(){
        i = new A();
    }
    public void toA(){
        i = new B();
    }
}

public class Main{
    public static void main(String[] args){
        C c = new C();
        c.f(); //=> "A f()"
        c.g(); //=> "A g()"

        c.toB();
        c.f(); //=> "B f()"
        c.g(); //=> "B g()"
    }
}

μƒμ†λŒ€μ‹  Delegationκ³Ό Interfaceλ₯Ό μ‚¬μš©ν•¨μœΌλ‘œμ¨ ν΄λž˜μŠ€λŠ” 훨씬 더 μœ μ—°ν•΄μ§„λ‹€.

Delegation Pattern μ‚¬μš©ν•˜λŠ” 이유?

  1. μ—¬λŸ¬ ν΄λž˜μŠ€μ—μ„œ κ²ΉμΉ˜λŠ” λ§€μ†Œλ“œλ₯Ό μ€„μ΄κΈ°λŠ”κ²ƒμ΄ ν•„μš”ν•˜κΈ° μœ„ν•΄ μ‚¬μš©

  2. ν•˜λ‚˜μ˜ 독립적인 행동이 ν•„μš”ν•˜μ§€λ§Œ, λ―Έλž˜μ— 이 행동이 λ°”λ€” 수 μžˆλŠ” μƒν™©μ—μ„œ μ‚¬μš©

  3. ν•˜λ‚˜μ˜ μƒμ†λœ ν˜•νƒœλ₯Ό μœ„μž„κ³Ό ν•¨κ»˜ μ‚¬μš©ν•˜κΈ° μœ„ν•΄ μ‚¬μš©

Last updated