source: src/main/java/onetomany/bargainingchipsgame/Stack.java@ 271

Last change on this file since 271 was 271, checked in by Tim Baarslag, 5 years ago

Immutable Chip and Stack

File size: 1.9 KB
Line 
1package onetomany.bargainingchipsgame;
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 */
11public 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;
21 quantity = q;
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 getPrice()
45 {
46 return price;
47 }
48
49 public String getColor()
50 {
51 return chip.getColor();
52 }
53
54 public boolean hasSameColorAs(Stack s)
55 {
56 return getChip().equals(s.getChip());
57 }
58
59 public Stack aggregateWith(Stack s)
60 {
61 if (s!=null && s.hasSameColorAs(this))
62 {
63 int q = quantity + s.getQuantity();
64 double p = (getPrice()*quantity+s.getPrice()*s.getQuantity())/q;
65 return new Stack(getChip(), p, q);
66 } else
67 throw new IllegalStateException("\n\n[Warning] StackClass::aggregateWith(Stack). Different colors! Aggregating "+s+" into "+this+" is not possible.");
68 }
69
70 @Override
71 public String toString()
72 {
73 return getQuantity()+"x"+getChip()+"($" + getPrice() + ")";
74 }
75
76 public static void main(String[] args)
77 {
78 Stack s = new Stack("Red", 9.0, 3);
79 Stack t = new Stack ("Red", 4.0, 2);
80 System.out.println(s + " + " + t + " = " + s.aggregateWith(t));
81 System.out.println(t + " + " + s + " = " + t.aggregateWith(s));
82 }
83}
Note: See TracBrowser for help on using the repository browser.