1 | package bargainingchips;
|
---|
2 |
|
---|
3 | /**
|
---|
4 | * Stack contains a number of {@link Chip} objects of the same color and price.
|
---|
5 | * A stack=(chip, quantity, price).
|
---|
6 | * Aggregation of a two stacks of the same colors, creates another stack with the total quantity but its chip in a new price equal to weighted average of the both unit prices.
|
---|
7 | * Aggregation of a stack with the empty stack is itself.
|
---|
8 | *
|
---|
9 | * Immutable.
|
---|
10 | */
|
---|
11 | public class Stack
|
---|
12 | {
|
---|
13 | private final Chip chip;
|
---|
14 | private final double price;
|
---|
15 | private final int quantity;
|
---|
16 |
|
---|
17 | public Stack(Chip c, double p, int q)
|
---|
18 | {
|
---|
19 | chip = c;
|
---|
20 | price = ( (p>0) ? p : 0.0);
|
---|
21 | quantity = ( (q>0) ? q : 0);
|
---|
22 | }
|
---|
23 |
|
---|
24 | public Stack(String c, double p, int q)
|
---|
25 | {
|
---|
26 | this(new Chip(c), p, q);
|
---|
27 | }
|
---|
28 |
|
---|
29 | /**
|
---|
30 | * @return the chip
|
---|
31 | */
|
---|
32 | public Chip getChip() {
|
---|
33 | return chip;
|
---|
34 | }
|
---|
35 |
|
---|
36 | /**
|
---|
37 | * @return the quantity
|
---|
38 | */
|
---|
39 | public int getQuantity()
|
---|
40 | {
|
---|
41 | return quantity;
|
---|
42 | }
|
---|
43 |
|
---|
44 | public double getUnitPrice()
|
---|
45 | {
|
---|
46 | return price;
|
---|
47 | }
|
---|
48 |
|
---|
49 | public double getTotalPrice()
|
---|
50 | {
|
---|
51 | return price * quantity;
|
---|
52 | }
|
---|
53 |
|
---|
54 | public String getColor()
|
---|
55 | {
|
---|
56 | return chip.getColor();
|
---|
57 | }
|
---|
58 |
|
---|
59 | public boolean hasSameColorAs(Stack s)
|
---|
60 | {
|
---|
61 | return getChip().equals(s.getChip());
|
---|
62 | }
|
---|
63 |
|
---|
64 | public Stack aggregateWith(Stack s)
|
---|
65 | {
|
---|
66 | if (s!=null && s.hasSameColorAs(this))
|
---|
67 | {
|
---|
68 | int q = quantity + s.getQuantity();
|
---|
69 | double p = (getUnitPrice()*quantity+s.getUnitPrice()*s.getQuantity())/q;
|
---|
70 | return new Stack(getChip(), p, q);
|
---|
71 | } else
|
---|
72 | throw new IllegalStateException("\n\n[Warning] StackClass::aggregateWith(Stack). Different colors! Aggregating "+s+" into "+this+" is not possible.");
|
---|
73 | }
|
---|
74 |
|
---|
75 | @Override
|
---|
76 | public String toString()
|
---|
77 | {
|
---|
78 | return getQuantity()+"x"+getChip()+"($" + getUnitPrice() + ")";
|
---|
79 | }
|
---|
80 |
|
---|
81 | public static void main(String[] args)
|
---|
82 | {
|
---|
83 | Stack s = new Stack("Red", 9.0, 3);
|
---|
84 | Stack t = new Stack ("Red", 4.0, 2);
|
---|
85 | System.out.println(s + " + " + t + " = " + s.aggregateWith(t));
|
---|
86 | System.out.println(t + " + " + s + " = " + t.aggregateWith(s));
|
---|
87 | }
|
---|
88 | }
|
---|