추가 부품 늘리기
ComputerDevice.class
public abstract class ComputerDevice {
public abstract int getPrice();
public abstract int getPower();
}
Keyboard.class
public class Keyboard extends ComputerDevice {
private int price;
private int power;
public Keyboard(int power, int price) {
this.power = power;
this.price = price;
}
public int getPrice() { return price; }
public int getPower() { return power; }
}
Monitor.class
public class Monitor extends ComputerDevice {
private int price;
private int power;
public Monitor(int power, int price) {
this.power = power;
this.price = price;
}
public int getPrice() { return price; }
public int getPower() { return power; }
}
Body.class
public class Body extends ComputerDevice {
private int price;
private int power;
public Body(int power, int price) {
this.power = power;
this.price = price;
}
public int getPrice() { return price; }
public int getPower() { return power; }
}
Computer.class
public class Computer extends ComputerDevice {
private List<ComputerDevice> components = new ArrayList<ComputerDevice>();
public void addComponent(ComputerDevice component) { components.add(component); }
public void removeComponent(ComputerDevice component) { components.remove(component); }
public int getPrice() {
int price = 0;
for(ComputerDevice component : components) {
price += component.getPrice();
}
return price;
}
public int getPower() {
int power = 0;
for(ComputerDevice component : components) {
power += component.getPower();
}
return power;
}
}
ComputerDevice
에 의해 각종 부품을 전달받아 List를 통해 저장한다.
<br/
Main.class
public static void main(String[] args) {
Keyboard keyboard = new Keyboard(5, 2);
Body body = new Body(100, 70);
Monitor monitor = new Monitor(20, 30);
Computer computer = new Computer();
computer.addComponent(keyboard);
computer.addComponent(body);
computer.addComponent(monitor);
int computerPrice = computer.getPrice();
int computerPower = computer.getPower();
}
참조: