๋ชฉ์ฐจ
์ด๋ค ์ํฉ์์ ์ฐ์ผ๊น?
๊ฒ์ ์บ๋ฆญํฐ๋ ๊ฐ๋ฐฉ์ ๋๋๊ฒ๊ณผ ์ฒด๋ ฅ๋ฌผ๋ต์ ๊ฐ์ง๊ณ ์๋ค
๋ณดํต ์์ดํ ์ ๋ง์ฐ์ค๋ฅผ ์ฌ๋ฆฌ๋ฉด ๊ฐ๊ฒฉ์ด ์ถ๋ ฅ๋๋๋ฐ,
๋๋๊ฒ ๊ฐ๊ฒฉ์ ์ถ๋ ฅํ๋๊ฒ์ด๋, ๊ฐ๋ฐฉ์ ๋ชจ๋ ์์ดํ ์ ๊ฐ๊ฒฉ์ ์ถ๋ ฅํ๋ ๊ฒ์ด๋
๊ฒ์ ์บ๋ฆญํฐ ์ ์ฅ์์ ๋์ผํ๊ฒ ๊ฐ๊ฒฉ์ ์ถ๋ ฅํ๋ ๊ฒ์ด๋ค.
๊ฐ๋ฐฉ์ ์์ดํ ์ ๋ด์ ์ ์๋ ๊ฒ์ด๋ ๊ฐ๋ฐฉ์.. ๊ฐ๊ฒฉ ์ถ๋ ฅ ๋ฉ์๋๊ฐ ์์ด์ผํ ๊น??
์๋๋ฉด ์์ดํ ์ ๊ฐ๊ฒฉ์ถ๋ ฅ ๋ฉ์๋๋ฅผ ์ถ๊ฐํด์
๊ฐ๋ฐฉ์ ๋ชจ๋ ์์ดํ ๊ฐ๊ฒฉ์ ์ถ๋ ฅํ ๋ ์์ดํ ์ ์ฒด๋ฅผ ์ํํด์ผํ ๊น???
์ปดํฌ์ง ํจํด์ด๋?
๊ทธ๋ฃน ์ ์ฒด์ ๊ฐ๋ณ ๊ฐ์ฒด๋ฅผ ๋์ผํ๊ฒ ์ฒ๋ฆฌํ ์ ์๋ ํจํด์ด๋ค.
ํด๋ผ์ด์ธํธ ์ ์ฅ์์ ์ ์ฒด๋ ๋ถ๋ถ์ด๋ ๋์ผํ ์ปดํฌ๋ํธ๋ก ์ธ์ํ ์ ์์ด์ผํ๋ค.
๋ค์๋งํด ์ผ๊ด์ ์ธ ๊ด๋ฆฌ๊ฐ ๊ฐ๋ฅํ๊ฒ๋ ๋๋ค!
* ํธ๋ฆฌ๊ตฌ์กฐ์ด์ด์ผ ํ๋ ์ ์ฝ์ฌํญ์ด ์๋ค!
์ฅ์
- ๋ณต์กํ ํธ๋ฆฌ ๊ตฌ์กฐ๋ฅผ ํธ๋ฆฌํ๊ฒ ์ฌ์ฉํ ์ ์๋ค
- ๋คํ์ฑ๊ณผ ์ฌ๊ท ํ์ฉ ๊ฐ๋ฅํ๋ค
- ์๋ก์ด ์๋ฆฌ๋จผํธ ํ์ ์ด ์ถ๊ฐ๋์ด๋ ํด๋ผ์ด์ธํธ ์ฝ๋๊ฐ ๋ณ๊ฒฝ๋์ง ์๋๋ค (printPrice(Component component))
๋จ์
- ๊ณตํต๋ ์ธํฐํ์ด์ค๋ฅผ ์ ์ํด์ผํ๊ธฐ ๋๋ฌธ์ ์ง๋์น๊ฒ ์ผ๋ฐํํด์ผํ๋ ๊ฒฝ์ฐ๋ ์๊ธธ ์ ์๋ค
(์ง๊ธ์ ์์ดํ ๊ณผ ๊ฐ๋ฐฉ์ด๋ ์ฐ๊ด์ฑ์ ์ฐพ์ ์ ์์ง๋ง.. ์์ ๋ค๋ฅธ ์ฐ๊ด๊ด๊ณ๋ฅผ ๊ฐ์ง๊ฒฝ์ฐ๋ ์คํ๋ ค ์ปดํฌ์งํจํด์ด ๋ฐ๋ชฉ์ ์ก๋๋ค!)
๊ตฌํ์ฝ๋
๊ธฐ์กด์ฝ๋
public class Client {
public static void main(String[] args) {
Item doranBlade = new Item("๋๋๊ฒ", 450);
Item healPotion = new Item("์ฒด๋ ฅ ๋ฌผ์ฝ", 50);
Bag bag = new Bag();
bag.add(doranBlade);
bag.add(healPotion);
Client client = new Client();
client.printPrice(doranBlade);
client.printPrice(bag);
}
private void printPrice(Item item) {
System.out.println(item.getPrice());
}
private void printPrice(Bag bag) {
int sum = bag.getItems().stream().mapToInt(Item::getPrice).sum();
System.out.println(sum);
}
}
์์ดํ ์ ํ์ด ์์ดํ ์ธ์ง, ๊ฐ๋ฐฉ์ธ์ง์ ๋ฐ๋ผ ๋ฉ์๋๋ฅผ ๋ค๋ฅด๊ฒ ๊ตฌํํด์ฃผ์ด์ผํ๋ค
public class Bag {
private List<Item> items = new ArrayList<>();
public void add(Item item) {
items.add(item);
}
public List<Item> getItems() {
return items;
}
}
๋ณ๊ฒฝ์ฝ๋
public interface Component {
int getPrice();
}
public class Bag implements Component {
private List<๐ฅComponent> components = new ArrayList<>();
public void add(๐ฅComponent component) {
components.add(component);
}
public List<๐ฅComponent> getComponents() {
return components;
}
@Override
public int getPrice() {
return components.stream().mapToInt(Component::getPrice).sum();
}
}
public class Client {
public static void main(String[] args) {
Item doranBlade = new Item("๋๋๊ฒ", 450);
Item healPotion = new Item("์ฒด๋ ฅ ๋ฌผ์ฝ", 50);
Bag bag = new Bag();
bag.add(doranBlade);
bag.add(healPotion);
Client client = new Client();
client.printPrice(doranBlade);
client.printPrice(bag);
}
private void printPrice(Component component) {
System.out.println(component.getPrice());
}
}
๊ฐ๋ฐฉ๊ณผ ์์ดํ ๋ชจ๋ Component๋ฅผ ๊ตฌํํ๊ณ ์์ด ๋์ผํ๊ฒ ์ทจ๊ธํ ์ ์๊ฒ๋์๋ค!
๊ฐ๋ฐฉ๊ณผ ์์ดํ ์ ๋ฐ๋ผ ๋ฌ๋ผ์ง๋ ๋ฉ์๋๋ฅผ Componentํ๋๋ก ์ค์ผ ์ ์๊ฒ๋์๋ค
'๐ฐ Design Pattern' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
Facade Pattern | ํผ์ฌ๋ ํจํด (0) | 2022.08.16 |
---|---|
Decorator Pattern | ๋ฐ์ฝ๋ ์ดํฐ ํจํด (0) | 2022.08.16 |
Bridge Pattern | ๋ธ๋ฆฟ์ง ํจํด (0) | 2022.08.15 |
Adapter Pattern | ์ด๋ํฐํจํด (0) | 2022.08.14 |
Prototype Pattern | ํ๋กํ ํ์ ํจํด (0) | 2022.08.14 |