目前Money还不够完善,比如没有考虑到值为负数的情况,这种情况应该是不存在的。下面重构Money类

    1. package com.lugew.springbootddd.snackmachine;
    2. import com.lugew.springbootddd.ValueObject;
    3. /**
    4. * @author 夏露桂
    5. * @since 2021/6/7 11:59
    6. */
    7. public class Money extends ValueObject<Money> {
    8. private final int oneCentCount;
    9. private final int tenCentCount;
    10. private final int quarterCount;
    11. private final int oneDollarCount;
    12. private final int fiveDollarCount;
    13. private final int twentyDollarCount;
    14. public Money(int oneCentCount, int tenCentCount, int quarterCount, int
    15. oneDollarCount, int fiveDollarCount, int twentyDollarCount) {
    16. if (oneCentCount < 0)
    17. throw new IllegalStateException();
    18. if (tenCentCount < 0)
    19. throw new IllegalStateException();
    20. if (quarterCount < 0)
    21. throw new IllegalStateException();
    22. if (oneDollarCount < 0)
    23. throw new IllegalStateException();
    24. if (fiveDollarCount < 0)
    25. throw new IllegalStateException();
    26. if (twentyDollarCount < 0)
    27. throw new IllegalStateException();
    28. this.oneCentCount = oneCentCount;
    29. this.tenCentCount = tenCentCount;
    30. this.quarterCount = quarterCount;
    31. this.oneDollarCount = oneDollarCount;
    32. this.fiveDollarCount = fiveDollarCount;
    33. this.twentyDollarCount = twentyDollarCount;
    34. }
    35. public static Money add(Money money1, Money money2) {
    36. return new Money(
    37. money1.oneCentCount + money2.oneCentCount,
    38. money1.tenCentCount + money2.tenCentCount,
    39. money1.quarterCount + money2.quarterCount,
    40. money1.oneDollarCount + money2.oneDollarCount,
    41. money1.fiveDollarCount + money2.fiveDollarCount,
    42. money1.twentyDollarCount + money2.twentyDollarCount);
    43. }
    44. @Override
    45. protected boolean equalsCore(Money other) {
    46. return oneCentCount == other.oneCentCount
    47. && tenCentCount == other.tenCentCount
    48. && quarterCount == other.quarterCount
    49. && oneDollarCount == other.oneDollarCount
    50. && fiveDollarCount == other.fiveDollarCount
    51. && twentyDollarCount == other.twentyDollarCount;
    52. }
    53. @Override
    54. protected int getHashCodeCore() {
    55. int hashCode = oneCentCount;
    56. hashCode = (hashCode * 397) ^ tenCentCount;
    57. hashCode = (hashCode * 397) ^ quarterCount;
    58. hashCode = (hashCode * 397) ^ oneDollarCount;
    59. hashCode = (hashCode * 397) ^ fiveDollarCount;
    60. hashCode = (hashCode * 397) ^ twentyDollarCount;
    61. return hashCode;
    62. }
    63. }

    👆任何字段的值为零得话,程序会抛出IllegalStateException()异常。