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