๋ฐ์ฝ๋ ์ดํฐ ํจํด (Decorator Pattern)
๊ธฐ์กด ๊ฐ์ฒด์ ์ฝ๋๋ฅผ ๋ณ๊ฒฝํ์ง ์๊ณ ๋ ๋์ ์ผ๋ก ์๋ก์ด ๊ธฐ๋ฅ์ ์ถ๊ฐํ ์ ์๊ฒ ํด์ฃผ๋ ๊ตฌ์กฐ ํจํด์
๋๋ค. ์์ ๋์ ํฉ์ฑ(Composition)์ ์ฌ์ฉํ์ฌ ๊ฐ์ฒด์ ๊ธฐ๋ฅ์ ์ ์ฐํ๊ฒ ํ์ฅํ ์ ์์ผ๋ฉฐ, ๋ฐํ์์ ๊ธฐ๋ฅ์ ์กฐํฉํ ์ ์๋ ์ฅ์ ์ด ์์ต๋๋ค.
์ฃผ์ ๋ชฉ์
โข
๊ฐ์ฒด์ ๋์ ์ผ๋ก ์๋ก์ด ์ฑ
์(๊ธฐ๋ฅ)์ ์ถ๊ฐ
โข
์์์ ํตํ ํ์ฅ์ ๋จ์ ์ ๋ณด์
โข
๋จ์ผ ์ฑ
์ ์์น(SRP)์ ์งํค๋ฉด์ ๊ธฐ๋ฅ ํ์ฅ ๊ฐ๋ฅ
ํน์ง
โข
๊ธฐ์กด ์ฝ๋๋ฅผ ์์ ํ์ง ์๊ณ ๊ธฐ๋ฅ ํ์ฅ ๊ฐ๋ฅ (๊ฐ๋ฐฉ-ํ์ ์์น)
โข
๋ฐ์ฝ๋ ์ดํฐ ๊ฐ์ฒด์ ์ค์ ๊ฐ์ฒด๊ฐ ๋์ผํ ์ธํฐํ์ด์ค ๊ตฌํ
โข
์ฌ๋ฌ ๋ฐ์ฝ๋ ์ดํฐ๋ฅผ ์กฐํฉํ์ฌ ๋ค์ํ ๊ธฐ๋ฅ ๊ตฌํ ๊ฐ๋ฅ
โข
์คํ ์ค์ ๋์ ์ผ๋ก ๊ธฐ๋ฅ ์ถ๊ฐ/์ ๊ฑฐ ๊ฐ๋ฅ
์์ ์ฝ๋
// Component ์ธํฐํ์ด์ค
interface Coffee {
double getCost();
String getDescription();
}
// ConcreteComponent
class SimpleCoffee implements Coffee {
public double getCost() { return 1.0; }
public String getDescription() { return "Simple Coffee"; }
}
// Decorator
abstract class CoffeeDecorator implements Coffee {
protected Coffee decoratedCoffee;
public CoffeeDecorator(Coffee coffee) {
this.decoratedCoffee = coffee;
}
public double getCost() { return decoratedCoffee.getCost(); }
public String getDescription() { return decoratedCoffee.getDescription(); }
}
// ConcreteDecorator
class Milk extends CoffeeDecorator {
public Milk(Coffee coffee) {
super(coffee);
}
public double getCost() { return super.getCost() + 0.5; }
public String getDescription() { return super.getDescription() + ", Milk"; }
}
Java
๋ณต์ฌ
์ฝ๋ ์ค๋ช
์ ์์ ์ฝ๋๋ ์ปคํผ ์ฃผ๋ฌธ ์์คํ
์ ํตํด ๋ฐ์ฝ๋ ์ดํฐ ํจํด์ ๊ตฌํํ ๊ฒ์
๋๋ค. ๊ฐ ๊ตฌ์ฑ์์๋ฅผ ์ดํด๋ณด๋ฉด:
โข
Coffee ์ธํฐํ์ด์ค (Component): ๊ธฐ๋ณธ ๊ธฐ๋ฅ์ ์ ์ํ๋ ์ธํฐํ์ด์ค๋ก, ๊ฐ๊ฒฉ(getCost)๊ณผ ์ค๋ช
(getDescription)์ ์ ๊ณตํฉ๋๋ค.
โข
SimpleCoffee ํด๋์ค (ConcreteComponent): Coffee ์ธํฐํ์ด์ค๋ฅผ ๊ตฌํํ ๊ธฐ๋ณธ ์ปคํผ ํด๋์ค์
๋๋ค. ๊ธฐ๋ณธ ๊ฐ๊ฒฉ๊ณผ ์ค๋ช
์ ์ ๊ณตํฉ๋๋ค.
โข
CoffeeDecorator ํด๋์ค (Decorator): ๋ฐ์ฝ๋ ์ดํฐ์ ๊ธฐ๋ณธ ํ์ ์ ๊ณตํ๋ ์ถ์ ํด๋์ค์
๋๋ค. Coffee ๊ฐ์ฒด๋ฅผ ํฌํจ(composition)ํ๊ณ ์์ต๋๋ค.
โข
Milk ํด๋์ค (ConcreteDecorator): ์ค์ ์ฅ์์ ๋ด๋นํ๋ ํด๋์ค๋ก, ์ปคํผ์ ์ฐ์ ๋ฅผ ์ถ๊ฐํ๋ ๊ธฐ๋ฅ์ ๊ตฌํํฉ๋๋ค. ๊ธฐ์กด ์ปคํผ์ ๊ฐ๊ฒฉ๊ณผ ์ค๋ช
์ ์ฐ์ ๊ด๋ จ ์ ๋ณด๋ฅผ ์ถ๊ฐํฉ๋๋ค.
์ด ํจํด์ ์ฌ์ฉํ๋ฉด ๋ค์๊ณผ ๊ฐ์ด ์ปคํผ์ ๋ค์ํ ์ต์
์ ๋์ ์ผ๋ก ์ถ๊ฐํ ์ ์์ต๋๋ค:
Coffee coffee = new SimpleCoffee();
coffee = new Milk(coffee); // ์ฐ์ ์ถ๊ฐ
// ํ์์ ๋ฐ๋ผ ๋ค๋ฅธ ๋ฐ์ฝ๋ ์ดํฐ(์คํ, ์๋ฝ ๋ฑ)๋ฅผ ๋ ์ถ๊ฐํ ์ ์์
Java
๋ณต์ฌ