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 ์ฌ์ฉํ๋ ์ด์ ?
์ฌ๋ฌ ํด๋์ค์์ ๊ฒน์น๋ ๋งค์๋๋ฅผ ์ค์ด๊ธฐ๋๊ฒ์ด ํ์ํ๊ธฐ ์ํด ์ฌ์ฉ
ํ๋์ ๋ ๋ฆฝ์ ์ธ ํ๋์ด ํ์ํ์ง๋ง, ๋ฏธ๋์ ์ด ํ๋์ด ๋ฐ๋ ์ ์๋ ์ํฉ์์ ์ฌ์ฉ
ํ๋์ ์์๋ ํํ๋ฅผ ์์๊ณผ ํจ๊ป ์ฌ์ฉํ๊ธฐ ์ํด ์ฌ์ฉ
Last updated
Was this helpful?