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

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

Immutable Chip and Stack

File size: 1.9 KB
RevLine 
[253]1package onetomany.bargainingchipsgame;
[233]2
3/**
[265]4 * Stack contains a number of {@link Chip} objects of the same color and price.
[271]5 * A stack=(chip, quantity, price).
[233]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.
[271]7 * Aggregation of a stack with the empty stack is itself.
[233]8 *
[271]9 * Immutable.
[233]10 */
[239]11public class Stack
12{
[271]13 private final Chip chip;
14 private final double price;
15 private final int quantity;
[233]16
[271]17 public Stack(Chip c, double p, int q)
[233]18 {
[265]19 chip = c;
[271]20 price = p;
[265]21 quantity = q;
[233]22 }
[266]23
[271]24 public Stack(String c, double p, int q)
[266]25 {
[271]26 this(new Chip(c), p, q);
[266]27 }
[271]28
[233]29 /**
30 * @return the chip
31 */
32 public Chip getChip() {
33 return chip;
34 }
35
36 /**
37 * @return the quantity
38 */
[239]39 public int getQuantity()
40 {
[233]41 return quantity;
42 }
43
44 public double getPrice()
45 {
[271]46 return price;
[233]47 }
48
[243]49 public String getColor()
50 {
51 return chip.getColor();
52 }
53
[257]54 public boolean hasSameColorAs(Stack s)
55 {
[271]56 return getChip().equals(s.getChip());
[257]57 }
58
[233]59 public Stack aggregateWith(Stack s)
60 {
[271]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);
[265]66 } else
67 throw new IllegalStateException("\n\n[Warning] StackClass::aggregateWith(Stack). Different colors! Aggregating "+s+" into "+this+" is not possible.");
68 }
[233]69
70 @Override
71 public String toString()
72 {
[271]73 return getQuantity()+"x"+getChip()+"($" + getPrice() + ")";
[233]74 }
[266]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 }
[233]83}
Note: See TracBrowser for help on using the repository browser.