design patterns : composite

This commit is contained in:
haerong22
2021-12-05 19:58:11 +09:00
parent 8e04fdf63a
commit 686fdec125
7 changed files with 130 additions and 0 deletions

View File

@@ -0,0 +1,22 @@
package composite.after;
import java.util.ArrayList;
import java.util.List;
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();
}
}

View File

@@ -0,0 +1,22 @@
package composite.after;
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());
}
}

View File

@@ -0,0 +1,5 @@
package composite.after;
public interface Component {
int getPrice();
}

View File

@@ -0,0 +1,18 @@
package composite.after;
public class Item implements Component {
private String name;
private int price;
public Item(String name, int price) {
this.name = name;
this.price = price;
}
@Override
public int getPrice() {
return this.price;
}
}

View File

@@ -0,0 +1,17 @@
package composite.before;
import java.util.ArrayList;
import java.util.List;
public class Bag {
private List<Item> items = new ArrayList<>();
public void add(Item item) {
items.add(item);
}
public List<Item> getItems() {
return items;
}
}

View File

@@ -0,0 +1,29 @@
package composite.before;
import java.util.stream.Collectors;
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);
}
}

View File

@@ -0,0 +1,17 @@
package composite.before;
public class Item {
private String name;
private int price;
public Item(String name, int price) {
this.name = name;
this.price = price;
}
public int getPrice() {
return this.price;
}
}