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 void List<Component> getComponents() {
return components;
}
@Override
public int getPrice() {
return components.stream().mapToInt(Component::getPrice).sum();
}
}
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;
}
}
Item와 Bag 별도로 알아야 하는 메서드를 별도로 만들어야 한다.
public class Client {
private void printPrice(Bag bag) {
int sum = bag.getItems().stream().mapToInt(Item.getPrice).sum();
System.out.println(sum);
}
private void printPrice(Item item) {
System.out.println(item.getPrice());
}
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);
}
}
public class Client {
private void printPrice(Component component) {
System.out.println(component.getPrice());
}
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);
}
}